简体   繁体   English

Java 正则表达式检查

[英]Java Regular Expression check

I have the code as我有代码

  String s = "The loading is completed, TB62 is bound for Chongqing, and trains 11-13 are expected";

    boolean matcher = Pattern.matches(".*11-13.*", s);
    System.out.println(matcher);

I am only checking for string containing 11-13 and above workds but if the regular expression is我只检查包含 11-13 及以上 workds 的字符串,但如果正则表达式是

.*1-13.*

that also works for the above string.这也适用于上述字符串。 How do I change regular expression that it will won't match .*1-13.* but only .*11-13.* should match如何更改它不会匹配的正则表达式.*1-13.*但只有.*11-13.*应该匹配

Updating and adding more info so people can answer更新和添加更多信息,以便人们可以回答

I have two regular expressions我有两个正则表达式

.*11-13.*
.*1-1.*

But the issue is even但问题是什

.*1-1.*  also matches to the string 




String s = "The loading is completed, TB62 is bound for Chongqing, and trains 11-13 are expected";

It should not match because I want to regular expression .*11-13.* to match only.它不应该匹配,因为我想正则表达式.*11-13.*只匹配。 I think I need to modify regular expression我想我需要修改正则表达式

For that use word boundary \b :为此使用单词边界\b

Pattern.matches(".*\\b11-13\\b.*", s);

Take a look at the javadoc of Pattern .看看Pattern的 javadoc。

For instance if you could have line breaks in the text, either use DOT_ALL (dot is also newline) with compile, or simply use find instead of match .例如,如果您可以在文本中使用换行符,请在 compile 中使用DOT_ALL (点也是换行符),或者简单地使用find而不是match

Instead of Pattern#matches , which matches the whole string, you can use Matcher#find as shown below:代替匹配整个字符串的Pattern#matches ,您可以使用Matcher#find ,如下所示:

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        String s = "The loading is completed, TB62 is bound for Chongqing, and trains 11-13 are expected";
        Matcher matcher = Pattern.compile("\\b11-13\\b").matcher(s);
        while (matcher.find()) {
            System.out.println(matcher.group());
        }

        // Alternatively
        Pattern.compile("11-13").matcher(s).results().map(MatchResult::group).forEach(System.out::println);
    }
}

Output: Output:

11-13
11-13

Note: \b is a boundary matcher .注意: \b是一个边界匹配器 If you need a regex for any pair of hyphen-separeted integers consisting of two digits, you can use \b\d{2}-\d{2}\b as the regex.如果您需要任何一对由两位数字组成的连字符分隔的整数的正则表达式,您可以使用\b\d{2}-\d{2}\b作为正则表达式。

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

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