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;
}
1 Answer 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 Details:
^: Line start(PM\\s*\\d+): Match and group text starting withPMfollowed by 0 or more whitespace followed by 1 or more digits/PM\\s*\\d+: Match/PMfollowed by 0 or more whitespace followed by 1 or more digits.*$: Match any # of characters before line end1ドル: 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);
}
PMappears nowhere in your regex. Did you see that?[0-9]matches one digit, not multiple such as17.//s+means "two forward slashes, literalscharacter repeated 1 to infinity times". You probably meant\\s+^PM\s*\d{2}