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

我正在寻找一个正则表达式。


文本示例


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

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


慕村225694
浏览 155回答 3
3回答

汪汪一只猫

您可以使用的一个可能的正则表达式是:^((\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和^将使$我们查看整个字符串。这\D*将确保空格后的子字符串中没有任何数字。并且确保始终有一个前导数字,在它之前有一个或多个\d+(其中是非负数)。(\d+\.)*#.#要提取此值,您可以将此正则表达式与 a 一起使用String.matches,.replaceFirst如下所示:// TODO: Give proper method nameString 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;}如果后面没有任何空格的单个数字(即"123")也应该匹配,则可以通过更改为对正则表达式进行细微修改\\D*$,( \\D*)?$以便空格变为可选。

HUH函数

Using(\d+\.)+\d不会匹配第一个条目,因为使用量词+它必须至少匹配一个数字和一个点。您可能会做的是使用锚^来断言字符串的开头并使用模式来匹配数字,然后重复匹配点和数字零次或多次,这样您也可以匹配第一个条目。匹配后,确保数字后面没有非空白字符。如果后面不能有更多数字,您可以使用额外的负前瞻。^\d+(?:\.\d+)*(?!\S)(?!.*\d)在 Java 中:String regex = "^\\d+(?:\\.\\d+)*(?!\\S)(?!.*\\d)";正则表达式演示解释^字符串的开始\d+(?:\.\d+)*匹配 1+ 位数字,后跟重复模式以匹配点和 1+ 位数字(?!\S)负前瞻检查左边的内容不是非空白字符(?!.*\d)负前瞻检查右边的内容不包含数字

繁华开满天机

我们可以尝试对每一行使用以下正则表达式模式:^(?!\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");}我已经根据您的所有输入对其进行了测试,它似乎正在工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java