简体   繁体   English

Java正则表达式匹配列表中的一个或多个字符

[英]Java Regular Expression match one or more characters in list

I have some strings: 我有一些字符串:

  • total 19xx.100 总计19xx.100
  • total 19x..100 总计19x..100
  • total 19..100 总共19..100
  • total 19x .100 总计19x .100

And I want to separate 19 with ("x" or "." one or more times) and 100. I tried to use regex: 我想将19与(“x”或“。”一次或多次)和100分开。我试图使用正则表达式:

 (x|\.)+

to group but it can not match all case above. 分组,但它不能匹配上面的所有情况。 Which regex can match all case above? 哪个正则表达式可以匹配上面的所有情况?

You can use regex: 你可以使用正则表达式:

public static Matcher split(String text) {
    Pattern pattern = Pattern.compile("(\\d+)(x*)(\\s*)(\\.*)(\\d+)");
    Matcher matcher = pattern.matcher(text);
    matcher.find();

    return matcher;
}

This regex works for test data: 此正则表达式适用于测试数据:

19xx.100
19x.100
19..100
19x .100

After then matcher.group(1) will return 19 and matcher.group(5) will return 100 之后matcher.group(1)将返回19matcher.group(5)将返回100

For your example, you could capture what is before 100 and 100 in 2 capturing groups: 对于您的示例,您可以捕获2个捕获组中100和100之前的内容:

(\\d+[x. ]+)(\\d+)

Explanation 说明

  • Capturing group (group 1) ( 捕获小组(第1组) (
  • Match one or more digits \\d+ 匹配一个或多个数字\\d+
  • Match one or more times x , . 匹配一次或多次x , . or whitespace [x. ]+ 或空白[x. ]+ [x. ]+ using a character class [x. ]+使用一个字符类
  • Close capturing group ) 关闭捕获组)
  • Capture in a group (group 2) one or more digits (\\d+) 在组(组2)中捕获一个或多个数字(\\d+)

You may use 你可以用

(\d+)(\s*[x.][x.\s]*)(\d+)

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

Details 细节

  • (\\d+) - Group 1: one or more digits (\\d+) - 第1组:一个或多个数字
  • (\\s*[x.][x.\\s]*) - Group 2: (\\s*[x.][x.\\s]*) - 第2组:
    • \\s* - 0+ whitespaces \\s* - 0+空格
    • [x.] - an x or . [x.] - x.
    • [x.\\s]* - 0+ chars that are either x , . [x.\\s]* - 0+字符是x , . or whitespace chars 或空白字符
  • (\\d+) - Group 3: one or more digits (\\d+) - 第3组:一个或多个数字

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

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