javaregexword-boundary

How do I change my regex to not match in the middle of words?


I have this code:

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 works. If however the regular expression is

.*1-13.*

it will also match the string. How do I change the regular expression .*1-13.* so that it won't match? Only .*11-13.* should match. Likewise, also .*1-1.* also matches, though it should not.


Solution

  • import java.util.regex.Pattern;
    
    public 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";
    
            boolean match1113 = Pattern.compile("\\b11-13\\b").matcher(s).find();
            boolean match11 = Pattern.compile("\\b1-1\\b").matcher(s).find();
    
            System.out.println("Matches 11-13: " + match1113);  // true
            System.out.println("Matches 1-1: " + match11);      // false
        }
    }