简体   繁体   English

给定字符串使用正则表达式从字符串中过滤出唯一元素

[英]Given string filter out unique element from string using regex

I have this String and I want to filter the digit that came after the big number with the space, so in this case I want to filter out 2 and 0.32.我有这个String ,我想用空格过滤大数字之后的数字,所以在这种情况下,我想过滤掉 2 和 0.32。 I used this regex below which only filters out decimal numbers, however I want to filter both decimals and integer numbers, is there any way?我在下面使用了这个正则表达式,它只过滤掉十进制数字,但是我想过滤小数和整数,有什么办法吗?

String s = "ABB123,ABPP,ADFG0/AA/BHJ.S,392483492389 2,BBBB,YUIO,BUYGH/AA/BHJ.S,3232489880 0.32"

regex = .AA/BHJ.S,\d+ (\d+.?\d+)正则表达式 = .AA/BHJ.S,\d+ (\d+.?\d+)

https://regex101.com/r/ZqHDQ8/1 https://regex101.com/r/ZqHDQ8/1

The problem is that \d+.?\d+ matches at least two digits.问题是\d+.?\d+至少匹配两位数。 \d+ matches one or more digits, then .? \d+匹配一个或多个数字,然后.? matches any optional char other than line break char, and then again \d+ matches (requires) at least one digit (it matches one or more).匹配除换行符以外的任何可选字符,然后\d+再次匹配(要求)至少一位数字(匹配一位或多位)。

Also, note that all literal dots must be escaped.另外,请注意,所有文字点都必须转义。

You can use您可以使用

.AA/BHJ\.S,\d+\s+(\d+(?:\.\d+)?)

See the regex demo .请参阅正则表达式演示

Details :详情

  • . - any one char - 任何一个字符
  • AA/BHJ\.S, - a AA/BHJ.S, string AA/BHJ\.S, - AA/BHJ.S,字符串
  • \d+ - one or more digits \d+ - 一位或多位数字
  • \s+ - one or more whitespaces \s+ - 一个或多个空格
  • (\d+(?:\.\d+)?) - Group 1: one or more digits, and then an optional sequence of a dot and one or more digits. (\d+(?:\.\d+)?) - 第 1 组:一个或多个数字,然后是一个点和一个或多个数字的可选序列。

You could look for anything following /AA/BHJ with a reluctant quantifier, then use a capturing group to look for either digits or one or more digits followed by a decimal separator and other digits.您可以使用不情愿的量词查找/AA/BHJ之后的任何内容,然后使用捕获组查找数字或一个或多个数字,后跟小数分隔符和其他数字。

/AA/BHJ.*?\s+(\d+\.\d+|\d+)

Here is a link to test the regex:这是测试正则表达式的链接:

https://regex101.com/r/l5nMrD/1 https://regex101.com/r/l5nMrD/1

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

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