简体   繁体   中英

Java Regex: how to use OR operation to extract substring

Now I am having a set of strings in the following two formats (mixed together):

1. /c/en/SUBSTRING
2. /c/en/SUBSTRING/some_other_string

And I want to use the single Java Regex to extract the SUBSTRING from the strings. I know how to do it for the the second case: Pattern.compile("^/c/en/(\\\\w+)/") . Obviously I can use two Regex, one for the first case and one for the second case, and then take the result of the successful one. But that is a waste of computation. How can I take the first case into consideration and use a single Regex to finish the task?

I tried "^/c/en/(\\\\w+)[/|$]" and "^/c/en/(\\\\w+)/|$" but they do not work. Thanks.

Just do:

Pattern.compile("^/c/en/([^/]+)")

and use a Matcher 's .find() against the input. The substring will be available in this matcher's .group(1) .

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