You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正则表达式问题:无法匹配含空格场景下的整数值

Fixing Regex Matching for studentId with Optional Spaces

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:27:37