【问题标题】:Java regex match number patternJava 正则表达式匹配数字模式
【发布时间】:2016-04-04 09:59:31
【问题描述】:

我想检查我的号码是否与正则表达式匹配。

我想要实现的是检查一个数字是否与模式匹配,而不是执行代码。

我的 if 语句如下:

public String refactorNumber(String input){
    if(input.matches("#,##0.##")) {
       //execute code
    }
}

但它永远不会匹配,我输入的数字是:

 - 0
 - 100
 - 1,100.01

我做错了什么?

【问题讨论】:

  • # 是干什么用的?
  • 这不是正则表达式。
  • # = 数字但不是强制性的
  • 老实说,我认为您应该阅读 String.matches() 的文档
  • # = number 但不是强制性的 -> matches() 应该如何理解*你自己的语法

标签: java regex number-formatting


【解决方案1】:

恐怕你还没有正确理解正则表达式的语法。

从您的示例代码看来,您正在尝试匹配一个数字,后跟一个逗号,后跟两位数,然后是零,后跟一个小数点,然后是两位数。

为此,您的正则表达式模式需要:

\d,\d{2}0\.\d{2}

找出模式的一个很好的资源是这个正则表达式备忘单:

https://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

很遗憾,该网站现在出现问题,因此您可以使用此 google 搜索找到它:

https://www.google.co.uk/search?q=regex+cheat+sheet&tbm=isch

【讨论】:

    【解决方案2】:

    你可以这样做(如果我做错了,请纠正我):

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public static void main(String[] args) {
    
        String input =" - 0\n"+
          " - 100\n"+
          " - 1,100.01\n"+
          " - 100,100,3\n"+
          " - 100,100,3.15\n"+
          "";  
        refactorNumber(input);  
    }
    
    public static void refactorNumber(String input){
        Matcher m = Pattern.compile("((?:\\d,)?\\d{0,2}0(?:\\.\\d{1,2})?)(?!\\d*,)").matcher(input);
        while (m.find()) {
            //execute code
        }
    

    【讨论】:

      【解决方案3】:

      这是我喜欢用来仅检测数字的简单代码行。

      if (input.matches("[0-9]*") {
      //code here
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-24
        • 2016-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多