如何用Regex匹配特定语句?Regex新手求助匹配指定格式内容
Hey there! Let's break this down step by step since you're new to regex—no worries, this is totally manageable.
First, let's start with a regex that fits your exact example, then unpack each part so you understand how it works:
^(.+?) @(.+?) (\d+) (\d+)$
Let's walk through each component:
^: Anchors the match to the start of the string (so we don't accidentally match partial lines)(.+?): The first capturing group for the band name..*matches any character,+means one or more of them, and?makes it non-greedy—this ensures it stops at the next@instead of gobbling up everything in the string.@: Matches the literal@with a space before it, exactly as it appears in your example.(.+?): The second capturing group for the venue name. Again, non-greedy so it stops right before the space leading to the price numbers.(\d+): The third capturing group for the price.\dmatches any digit,+means one or more digits, with a space before it to separate from the venue.(\d+): The fourth capturing group for the quantity—same logic as the price, capturing all trailing digits.$: Anchors the match to the end of the string (ensures there's no extra, unwanted text after the quantity).
Testing with your example
If you run this regex against Band Name @Venue 30 450, you'll get these results from the capturing groups:
Band Name(band name)Venue(venue name)30(price)450(quantity)
Adjustments for edge cases
If your band/venue names might include special characters (like hyphens, apostrophes, or ampersands), the regex still works because . matches any character except newlines. If you want to restrict to only letters, spaces, and common symbols, you could swap (.+?) for ([\w\s'-]+?)—this allows letters, numbers, spaces, apostrophes, and hyphens.
Quick example in code (Python)
If you're using Python to implement this, here's how it might look:
import re input_text = "Band Name @Venue 30 450" regex_pattern = r"^(.+?) @(.+?) (\d+) (\d+)$" match_result = re.match(regex_pattern, input_text) if match_result: band = match_result.group(1) venue = match_result.group(2) price = match_result.group(3) quantity = match_result.group(4) print(f"Band: {band}, Venue: {venue}, Price: {price}, Quantity: {quantity}")
That should cover your use case! Let me know if you need tweaks for any specific variations in your actual data.
内容的提问来源于stack exchange,提问作者Shrexpecial

