在C#中使用正则表达式解析含文本与正负数字的三段字符串
Got it, let's work through this regex problem step by step. Since you didn't share the exact structure of your target string, I'll start with a common, straightforward scenario where the text section comes first (with any number of words), followed by the two positive/negative numbers — and I’ll also show how to tweak things if your string has a different layout.
We need to capture three distinct parts: free-form text, a signed number, another signed number. Here's how to build the pattern:
Basic Version (Text First, Integers Only)
This works for strings like "Quick brown fox -42 123" or "Hello -100 0":
^(.+?)\s+(-?\d+)\s+(-?\d+)$
Let’s break down each component:
^&$: Anchors to match the entire string, so we don’t pick up partial matches(.+?): Non-greedy capture group for the text. The+?ensures we stop at the first whitespace before the first number (instead of gobbling up everything greedily)\s+: Matches one or more spaces to separate the text and numbers(-?\d+): Capture groups for the numbers.-?allows an optional negative sign,\d+matches one or more digits (for integers)
Support for Decimal Numbers
If your numbers can be decimals (like -3.14 or 2.718), adjust the number capture groups to handle decimal points:
^(.+?)\s+(-?\d+(\.\d+)?)\s+(-?\d+(\.\d+)?)$
The (\.\d+)? adds an optional decimal part to the number pattern.
Adjust for Different String Layouts
If your numbers come before the text (e.g., "-10 20 Some random text here"), just reorder the capture groups:
^(-?\d+)\s+(-?\d+)\s+(.+)$
Here’s how to use this regex in practice to extract the three parts:
import re # Example target string target_string = "The quick brown fox jumps over the lazy dog -99 1234" # Use the integer regex pattern pattern = r"^(.+?)\s+(-?\d+)\s+(-?\d+)$" match_result = re.match(pattern, target_string) if match_result: extracted_text = match_result.group(1) first_number = int(match_result.group(2)) second_number = int(match_result.group(3)) print(f"Extracted Text: {extracted_text}") print(f"First Number: {first_number}") print(f"Second Number: {second_number}") else: print("Error: String doesn't match the expected format!")
For decimals, just replace int() with float() and use the decimal regex pattern.
- Non-greedy matching is critical: Using
(.+)instead of(.+?)would make the text capture group greedily consume everything up to the last number, breaking the match. - Handle extra whitespace: If your string might have leading/trailing spaces, add
\s*at the start and end of the regex:^\s*(.+?)\s+(-?\d+)\s+(-?\d+)\s*$ - Text with numbers: If your text section includes numbers (e.g.,
"Text with 123 here -45 67"), you’ll need a clear separator (like|or;) instead of spaces. For example, use^(.+?)\|(-?\d+)\|(-?\d+)$for strings formatted like"Text with 123 here|-45|67".
内容的提问来源于stack exchange,提问作者Bobbler

