【问题标题】:Check string for characters, without getting hung up on spaces检查字符串中的字符,而不会挂在空格上
【发布时间】:2014-03-31 20:05:51
【问题描述】:

目前,在我的程序中,我通过使用以下 Regex 方法和 if 语句来检查我的字符串是否不是整数值:

if(Regex.IsMatch(myString, @"^\d+$") == false) {}

但是,我需要允许以下值:“45 23 12”。这些值涉及空格,我认为Regex 将其视为字符,因为每当我尝试上一个示例时,我的代码都会返回 false。

如何在允许使用空格的同时检查非整数值?

This question 使用Regex.Matches(myString,@"[a-zA-Z]").Count 来检查字符串中出现的所有来自“a-z”的字符,这不涉及“”。但是,当我在 ifstatement 中使用它时,我注意到它是 Int 类型,无法与 false 和 == 进行比较。

【问题讨论】:

  • 不要将Matches 放在你的 if 语句中。将其更改为IsMatch
  • “45 23 12”是否应该被视为单个整数?
  • @Malk 不,他们是独立的

标签: c# regex wpf string integer


【解决方案1】:
if(! Regex.IsMatch(myString, @"^\s*\d(\d|\s)*$")) { ... }

【讨论】:

    【解决方案2】:

    我会使用正则表达式

    ^\d+(\s\d+)*$
    

    解释:

    ^          beginning of line.
    \d+        one or more digits.
    (\s\d+)*   zero, one or more repetitions of space + one or more digits.
    $          end of line.
    
    if (!Regex.IsMatch(myString, @"^\d+(\s\d+)*$")) {
        ...
    }
    

    请写下

    !<boolean expression> 而不是<boolean expression> = false。

    和

    <Boolean expression> 而不是<Boolean expression> = true。

    你不写1 * x,而只是写x。

    很多人认为 if 语句需要比较。他们不。他们需要的是一个布尔表达式,即一个产生true 或false 值的表达式。 Regex.IsMatch(...) 返回一个 bool 值,这就是我们所需要的。

    【讨论】:

      【解决方案3】:

      尝试以下正则表达式(如果我正确理解您的问题。

      ^(?:\d|\s)+$
      

      它似乎做你想做的事和here is the test for it。

      【讨论】:

        猜你喜欢
        • 2015-05-29
        • 2011-01-03
        • 2011-03-19
        • 1970-01-01
        • 2021-12-07
        • 1970-01-01
        • 2022-06-25
        • 1970-01-01
        相关资源
        最近更新 更多