开发者

Need help with regular expression when only one number changes in string

开发者 https://www.devze.com 2023-03-22 12:43 出处:网络
How to check in Java with regular 开发者_JAVA百科expression if some string matches with Monday ptnumber Operating Mode

How to check in Java with regular 开发者_JAVA百科expression if some string matches with

Monday ptnumber Operating Mode

where number ( after pt ) has concrete value like 0,1,...99,.. - any integer? Mondaypt and Operating mode are hardcoded just number can change in string.


@Mark Peters & @Joachim Sauer gave good answer. But I'd like to add short comment.

use \d instead of [0-9] and \s+ instead of space, i.e. "Monday\\s+\\d+\\s+Operating Mode". Now the regex is less strict: it allows number of spaces. For me \d is more readable than [0-9]

  1. method matches automatically adds ^ in the beginning and $ in the end of regex. Use Matchermfind() instead.

  2. Compilation of pattern is very CPU intensive process. It is good practice to use Pattern.compile() for all static patterns during the application initialization and then use the ready pattern. String.mantches() actually creates pattern and then runs it.

private static Pattern p = Pattern.compile("Monday\\s+\\d+\\s+Operating Mode");

// now use it:

p.matcher(str).find();


boolean matches = input.matches("Monday pt[0-9]+ Operating Mode");


This will also extract the number.

String input ="Monday pt23 Operating Mode";
Pattern p = Pattern.compile("Monday pt([0-9]+) Operating Mode");
Matcher m = p.matcher(input);
boolean found = m.find();
if (found) {
    String number = m.group(1);
    System.out.println(number);
}


String input = "Monday 24 Operating Mode";
if ( input.matches ( "Monday [0-9]+ Operating Mode" ) ) {
    //...it matches...
}


How about input.matches("Monday \\d{0,2} Operating Mode");


input.matches("Monday pt(\\d+) Operating Mode");
0

精彩评论

暂无评论...
验证码 换一张
取 消