xybrek xybrek - 5 months ago 22
Java Question

Regex to match words after forward slash or in between

I have this code that needs to get words after

/
or in between this character.

Pattern pattern = Pattern.compile("\\/([a-zA-Z0-9]{0,})"); // Regex: \/([a-zA-Z0-9]{0,})
Matcher matcher = pattern.matcher(path);
if(matcher.matches()){
return matcher.group(0);
}


The regex
\/([a-zA-Z0-9]{0,})
works but not in Java, what could be the reason?

Answer

You need to get the value of Group 1 and use find to get a partial match:

Pattern pattern = Pattern.compile("/([a-zA-Z0-9]*)");
Matcher matcher = pattern.matcher(path);
if(matcher.find()){
   return matcher.group(1);  // Here, use Group 1 value
}

Matcher.matches requires a full string match, only use it if your string fully matches the pattern. Else, use Matcher.find.

Since the value you need is captured into Group 1 (([a-zA-Z0-9]*), the subpattern enclosed with parentheses), you need to return that part.

You needn't escape the / in Java regex. Also, {0,} functions the same way as * quantifier (matches zero or more occurrences of the quantified subpattern).

Also, [a-zA-Z0-9] can be replaced with \p{Alnum} to match the same range of characters (see Java regex syntax reference. The pattern declaration will look like

"/(\\p{Alnum}*)"
Comments