regex如何在Java中找到多个模式(使用Matcher)
假设我有一个String
,比如one two three one one two one
。
现在我使用Pattern
和Matcher
来查找String
中的任何特定Pattern
。
像这样:
Pattern findMyPattern = Pattern.compile("one");
Matcher foundAMatch = findMyPattern.matcher(myString);
while(foundAMatch.find())
// do my stuff
但是,假设我想找到多种模式。对于我举的例子String
,我想同时找到one
和two
。现在它是一个非常小的字符串,所以可能的解决方案是使用另一个Pattern
并找到我的匹配项。但是,这只是一个小例子。有没有一种有效的方法来做这件事,而不是在所有的Pattern
集合中循环尝试
# 1 楼答案
使用正则表达式的功能:更改模式以匹配
one
或two
# 2 楼答案
这并不能解决我的问题,这样我们就可以把(一|二)变成一个特定的字符串
但我的要求是改变 模式一->;三&;二->;四个