简体   繁体   English

正则表达式比较字符串中的数字

[英]regex to compare numbers from string

I have strings like: 我有这样的字符串:

1.2.3
1.4.0.136
V312
V10
2.2.2
r1elease2.0.0
Vr 1.5.1

I want to get regex that should extract versions (without string) out of these strings and arrange in sorter order. 我想获得正则表达式,该正则表达式应从这些字符串中提取版本(无字符串)并按排序顺序排列。 Any two strings can be passed at a time to compare. 一次可以传递任何两个字符串进行比较。

1.2.3 should become 1.2.3 (no change)
1.4.0.136 should become 1.4.0.136 (no change)
V312 should become 312 
V10 should become 10
2.2.2 should become 2.2.2 (no change)
r1elease2.0.0 should become 2.0.0
Vr 1.5.1 should become 1.5.1

I tried /[^0-9\\.]+/g but it didn't worked in case r1elease2.0.0 as this string became 12.0.0 which is incorrect. 我试过/[^0-9\\.]+/g但在r1elease2.0.0情况下r1elease2.0.0因为此字符串变为12.0.0 ,这是不正确的。

For you example data, you could use: 对于示例数据,可以使用:

\\d+(?:\\.\\d+)*\\b

This will match one or more digits followed by a zero or more times repeated pattern of a dot and one or more digits. 这将匹配一个或多个数字,后跟一个零或多个重复的点和一个或多个数字的重复模式。 It ends with a word boundary \\b so the 1 in r1elease2.0.0 does not match. 它以单词边界\\b结尾,因此r1elease2.0.0中的1不匹配。

Explanation 说明

  • \\d+ One or more digits \\d+一个或多个数字
  • (?: Non capturing group (?:非捕获组
    • \\.\\d+ Match a dot and one or more digits \\.\\d+匹配一个点和一个或多个数字
  • )* Close non capturing group and repeat zero or more times )*关闭非捕获组并重复零次或多次
  • \\b Word boundary \\b字边界

Try: 尝试:

(?<=^|[\w\s])\d+(?:\.?\d+)*$

Demo 演示版

You can do: 你可以做:

(\\w\\s?)*?(\\d+(?:\\.\\d+)*\\b)

and perform the replacement with captured group 2. The part with \\d+(?:\\.\\d+)*\\b was explained by The fourth birth. 并用捕获的组2进行替换。 \\d+(?:\\.\\d+)*\\b部分由第四胎解释。 The part (\\w\\s?)*? 部分(\\w\\s?)*? gets discarded in the replacement. 在替换中被丢弃。 Output: 输出:

1.2.3
1.4.0.136
312
10
2.2.2
2.0
1.5.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM