简体   繁体   中英

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?

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}*)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM