【问题标题】:Regex- Whitespace is not working to get an integer value正则表达式 - 空白无法获取整数值
【发布时间】:2021-12-14 17:13:46
【问题描述】:

我正在尝试使用正则表达式进行模式匹配。如果消息在模式字符串后有空格,则得到一个空字符串。

string str = "studentId: 1234, Name: Hello";
Regex reg = new Regex(@"studentId:(\d*)", RegexOptions.IgnoreCase);

Match m = reg.Match(str);
Group g = m.Groups[1];
int Id = int.Parse(g.ToString());

studentId:1234(工作) 学生 ID:1234(不工作) studentId:1234(不工作)

我需要得到 1234 的值而不考虑空格。

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    是的,您需要匹配空白字符。

    Regex reg = new Regex(@"studentId:\s*(\d+)", RegexOptions.IgnoreCase);
    

    详情

    • studentId: - 固定字符串
    • \s* - 零个或多个空格
    • (\d+) - 一位或多位数字(第 1 组)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-26
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多