【问题标题】:Regex for numeric portion of Java stringJava字符串数字部分的正则表达式
【发布时间】:2012-12-24 07:12:40
【问题描述】:

我正在尝试编写一个 Java 方法,它将一个字符串作为参数,如果它匹配一个模式,则返回另一个字符串,否则返回 null。模式:

  • 以数字开头(1 位以上);然后是
  • 冒号(“:”);然后是
  • 单个空格(“”);然后是
  • 任何 1+ 个字符的 Java 字符串

因此,一些与此模式匹配的有效字符串:

50: hello
1: d
10938484: 394958558

还有一些与此模式匹配的字符串:

korfed49
: e4949
6
6:
6:sdjjd4

该方法的大致框架是这样的:

public String extractNumber(String toMatch) {
    // If toMatch matches the pattern, extract the first number
    // (everything prior to the colon).

    // Else, return null.
}

这是我迄今为止最好的尝试,但我知道我错了:

public String extractNumber(String toMatch) {
    // If toMatch matches the pattern, extract the first number
    // (everything prior to the colon).
    String regex = "???";
    if(toMatch.matches(regex))
        return toMatch.substring(0, toMatch.indexOf(":"));

    // Else, return null.
    return null;
}

提前致谢。

【问题讨论】:

    标签: java regex


    【解决方案1】:

    你的描述是正确的,现在只需要翻译成正则表达式:

    ^      # Starts
    \d+    # with a number (1+ digits); then followed by
    :      # A colon (":"); then followed by
           # A single whitespace (" "); then followed by
    \w+    # Any word character, one one more times
    $      # (followed by the end of input)
    

    在 Java 字符串中给予:

    "^\\d+: \\w+$"
    

    您还想捕获数字:在 \d+ 周围加上括号,使用 Matcher,如果匹配,则捕获第 1 组:

    private static final Pattern PATTERN = Pattern.compile("^(\\d+): \\w+$");
    
    // ...
    
    public String extractNumber(String toMatch) {
        Matcher m = PATTERN.matcher(toMatch);
        return m.find() ? m.group(1) : null;
    }
    

    注意:在 Java 中,\w 仅匹配 ASCII 字符和数字(例如,.NET 语言不是这种情况),它也将匹配下划线。如果你不想要下划线,你可以使用(Java 特定的语法):

    [\w&&[^_]]
    

    而不是\w 作为正则表达式的最后一部分,给出:

    "^(\\d+): [\\w&&[^_]]+$"
    

    【讨论】:

    • @smit 是的,鉴于使用了.matches() 方法——我真的很讨厌这个方法的名字,Java 在那里犯了一个错误
    • 我不明白你的意思。你能说得清楚一点吗?
    • @smit:当你使用.matches()时,就像你用^$包围整个正则表达式——与正则表达式匹配的定义相矛盾,这可能发生在任何地方输入。 真正的 Java 中的正则表达式匹配是使用.find() 完成的。
    • 我明白你的意思。阅读 java doc 后,它变得更加清晰。我认为这个链接可能很有用。 matches and find
    【解决方案2】:

    尝试使用以下命令:\d+: \w+

    【讨论】:

      猜你喜欢
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多