正则表达式问题:无法匹配含空格场景下的整数值
Got it, let's sort out this regex problem you're facing! The issue with your current pattern is that it expects studentId: to be immediately followed by digits—no room for any spaces in between. That's why cases with a space after the colon fail to capture the ID.
The Fix: Allow Optional Whitespace
Modify your regex to include \s* right after the colon. This matches zero or more whitespace characters (spaces, tabs, etc.), so it works whether there's a space, multiple spaces, or no space at all. Also, I'd swap \d* for \d+—* matches zero or more digits, which could lead to an empty string that breaks int.Parse(), while + ensures at least one digit exists.
Here's the updated code:
string str = "studentId: 1234, Name: Hello"; Regex reg = new Regex(@"studentId:\s*(\d+)", RegexOptions.IgnoreCase); Match m = reg.Match(str); Group g = m.Groups[1]; int Id = int.Parse(g.ToString()); // Now correctly gets 1234, even with spaces!
Quick Breakdown:
\s*: Matches 0 or more whitespace characters (handles the optional space after the colon)(\d+): Captures one or more digits (avoids empty string matches that would crash the parse)
If you specifically only want to allow spaces (not tabs or other whitespace), you can replace \s* with * (a space followed by *), but \s* is more flexible for real-world input.
内容的提问来源于stack exchange,提问作者Ullan

