简体   繁体   English

Java Regex-在号码匹配方面需要帮助

[英]Java Regex - need help on number match

I am trying to match all the values 1 to 18 from string 24-15-7-49-63-2 using regex. 我正在尝试使用正则表达式匹配字符串24-15-7-49-63-2中的所有值118 I used regex before for general purpose but I don't have any idea how to do it. 我以前使用regex做一般用途,但我不知道该怎么做。

The tricky thing is that you cannot easily define ranges with regexes. 棘手的是,您无法轻松地使用正则表达式定义范围。 But this might do what you want: 但这可能会满足您的要求:

\b([1-9]|1[0-8])\b

You can see it in action here: http://regexr.com?2v8jj 您可以在此处查看其运行情况: http : //regexr.com?2v8jj

Here's an example in java: 这是java中的示例:

String text = "24-15-7-49-63-2";
String pattern = "\\b([1-9]|1[0-8])\\b";

Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(text);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Outputs: 输出:

15
7
2

Edit: Based on the comment you can get unique matches using this pattern: 编辑:根据注释,您可以使用以下模式获得唯一的匹配项:

\b([1-9]|1[0-8])\b(?!.*\b\1\b.*)

In action: http://regexr.com?2v8kh 实际使用中: http//regexr.com?2v8kh

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

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