java - Java 字符串数字部分的正则表达式

标签 java regex

我正在尝试编写一个 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;
}

提前致谢。

最佳答案

您的描述很准确,现在只需要将其翻译成正则表达式即可:

^      # 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&&[^_]]+$"

关于java - Java 字符串数字部分的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14248775/

相关文章:

java - generateCertificate() 时发生 CertificateException

Java Mockito 当接受参数但有条件时

java - 在同一服务器内使用来自不同域的两个数据库

java - JFrame对事件是半透明/透明的,但仍然可见

javascript - jQuery/JavaScript : regex to replace instances of an html tag

java - 如何使用一个类中的静态变量来更新另一个类中的非静态实例变量?

regex - 正则表达式中什么是零宽度独立子表达式?

php - 如何使用 php 查找并删除字符串中的最后一个链接标签?

javascript - 正则表达式构建字符串直到遇到第 N 个匹配项

java - 从字符串中删除 HTML - RSS