简体   繁体   中英

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

.*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

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. I think I need to modify regular expression

For that use word boundary \b :

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

Take a look at the javadoc of Pattern .

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 .

Instead of Pattern#matches , which matches the whole string, you can use Matcher#find as shown below:

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:

11-13
11-13

Note: \b is a boundary matcher . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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