[英]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. 我想使用单个Java Regex从字符串中提取SUBSTRING。 I know how to do it for the the second case:
Pattern.compile("^/c/en/(\\\\w+)/")
. 我知道如何为第二种情况做这件事:
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?
如何考虑第一个案例并使用单个Regex完成任务?
I tried "^/c/en/(\\\\w+)[/|$]"
and "^/c/en/(\\\\w+)/|$"
but they do not work. 我试过
"^/c/en/(\\\\w+)[/|$]"
和"^/c/en/(\\\\w+)/|$"
但它们不起作用。 Thanks. 谢谢。
Just do: 做就是了:
Pattern.compile("^/c/en/([^/]+)")
and use a Matcher
's .find()
against the input. 并使用
Matcher
的.find()
对输入。 The substring will be available in this matcher's .group(1)
. 子字符串将在此匹配器的
.group(1)
可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.