mgr
mgr

Reputation: 651

java String regex pattern match and replace string

There is a string, if that pattern matches need to return first few char's only.

String str = "PM 17/PM 19 - Test String"; 

expecting return string --> PM 17

Here my String pattern checking for:

1) always starts with PM
2) then followed by space (or some time zero space)
3) then followed by some number
4) then followed by slash (i.e. /)
5) then followed by Same string PM
6) then followed by space (or some time zero space)
7) Then followed by number
8) then any other chars/strings.

If given string matches above pattern, I need to get string till before the slash (i.e. PM 17)

I tried below way but it did not works for the condition.

  if(str.matches("PM\\s+[0-9.]/PM(.*)")) { //"PM//s+[0-9]/PM(.*)"
                  str = str.substring(0, str.indexOf("/"));
                  flag = true;
  } 

Upvotes: 1

Views: 1657

Answers (1)

anubhava
anubhava

Reputation: 784998

Instead of .matches you may use .replaceFirst here with a capturing group:

str = str.replaceFirst( "^(PM\\s*\\d+)/PM\\s*\\d+.*$", "$1" );
//=> PM 17

RegEx Demo

RegEx Details:

  • ^: Line start
  • (PM\\s*\\d+): Match and group text starting with PM followed by 0 or more whitespace followed by 1 or more digits
  • /PM\\s*\\d+: Match /PM followed by 0 or more whitespace followed by 1 or more digits
  • .*$: Match any # of characters before line end
  • $1: is replacement that puts captured string of first group back in the replacement.

If you want to do input validation before substring extraction then I suggest this code:

final String regex = "(PM\\s*\\d+)/PM\\s*\\d+.*";    
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(str);

if (matcher.matches()) {
    flag = true;
    str = matcher.group(1);
}

Upvotes: 1

Related Questions