xybrek xybrek - 1 year ago 81
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);
return matcher.group(0);

The regex
works but not in Java, what could be the reason?

Answer Source

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);
   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