1

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;
  } 
8
  • 1
    PM appears nowhere in your regex. Did you see that? Commented Oct 8, 2019 at 15:17
  • corrected it with PM. Commented Oct 8, 2019 at 15:18
  • next issue: [0-9] matches one digit, not multiple such as 17. Commented Oct 8, 2019 at 15:19
  • 3
    //s+ means "two forward slashes, literal s character repeated 1 to infinity times". You probably meant \\s+ Commented Oct 8, 2019 at 15:19
  • try ^PM\s*\d{2} Commented Oct 8, 2019 at 15:25

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.