正则表达式,用于提取带有可选点的前导数字

时间:2019-01-29 15:58:29

标签: java regex

我正在寻找正则表达式。

文本示例

1 Match
1.1 Match
45.67.21234.3 Match
1 Does not match1
12. Does not match

提取/匹配的值应为:

1
1.1
45.67.21234.31

这些不匹配:

1 Does not match1 // no match because of an additional digit in the text
12. Does not match // no match because of the dot after 12

到目前为止,我的正则表达式看起来像这样:

(\d+\.)+\d

但这与第一个条目不匹配。

3 个答案:

答案 0 :(得分:1)

使用(\d+\.)+\d将不匹配第一个条目,因为使用量词+必须至少将一个数字和一个点匹配一次。

您可能要做的是使用锚点^来声明字符串的开头,并使用模式来匹配数字,然后重复将点和数字匹配零次或多次,以便也匹配第一个条目。

匹配后,请确保数字后没有非空格字符。如果后面没有其他数字,则可以使用额外的负前瞻。

^\d+(?:\.\d+)*(?!\S)(?!.*\d)

在Java中:

String regex = "^\\d+(?:\\.\\d+)*(?!\\S)(?!.*\\d)";

Regex demo

说明

  • ^字符串的开头
  • \d+(?:\.\d+)*匹配1个以上的数字,后跟一个重复的模式以匹配点和1个以上的数字
  • (?!\S)负向查找以检查左侧是否不是非空白字符
  • (?!.*\d)进行负向查找以检查右边的内容是否不含数字

答案 1 :(得分:1)

您可以使用的可能的正则表达式是:

^((\d+\.)*\d+) \D*$

捕获组1将在哪里举行比赛。

说明:

^              # Start of the String
 (             # Open capture group 1:
  (\d+\.)      #  One or more digits, followed by a dot
         *     #  Repeated 0 or more times
          \d+  #  Followed by 1 or more digits
 )             # Closing capture group 1
               # Followed by a space
   \D*         # Followed by 0 or more non-digits
$              # Followed by the end of the String

^$将使我们研究整个String。 \D*将确保空格后的子字符串中没有任何数字。并且\d+之后的(\d+\.)*确保始终有一个前导数字,其前有一个或多个#.(其中#是非负数)。< / p>

要提取此值,可以将此正则表达式与String.matches.replaceFirst一起使用,如下所示:

// TODO: Give proper method name
String test(String str){
  String regex = "^((\\d+\\.)*\\d+) \\D*$";
  if(str.matches(regex))
    return str.replaceFirst(regex, "$1");
    // The `$1` will leave just the match of the first capture group,
    // removing everything else we don't need
  else
    return null;
}

Try it online.

如果单个数字后面也没有空格(即"123")也应匹配,则可以通过将\\D*$更改为( \\D*)?$来对正则表达式进行细微修改。变为可选。

Try it online.

答案 2 :(得分:0)

我们可以针对每行尝试使用以下正则表达式模式:

^(?!\D*\d[^0-9.]+\d).*\b\d+(?:\.\d+)?(?=\\s|$).*$

说明:

^                            from the start of the line
    (?!\D*\d[^0-9.]+\d)      assert that two (or more) separate numbers
                             do not occur in the line
    .*                       then consume anything, up to
    \b\d+(?:\.\d+)?          an integer, or complete decimal
    (?=\\s|$)                where either a space or the end of the line follows
    .*                       then consume anything, up to
$                            the end of the line

以下是使用此模式的Java代码:

String line = "45.67.21234.3";
String pattern = "^(?!\\D*\\d[^0-9.]+\\d).*\\b\\d+(?:\\.\\d+)?(?=\\s|$).*$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find()) {
    System.out.println("match");
}
else {
    System.out.println("no match");
}

我已经根据您的所有输入对它进行了测试,它似乎可以正常工作。