This question already has an answer here:
这个问题在这里已有答案:
- My regex is matching too much. How do I make it stop? 5 answers
我的正则表达式匹配得太多了。我怎么让它停下来? 5个答案
I'm trying to strip a string of all sequences that begin with a string "GUGU" and and end with something like "AGAG". The closest I've gotten is
我正在尝试删除一个以字符串“GUGU”开头的所有序列的字符串,并以“AGAG”之类的结尾。我得到的最接近的是
replaceAll("GUGU(.*)AGAG", "")
but all that does is replace the "largest" instance. Meaning if there are multiple occurrences of GUGU*AGAG in a string, it only matches the outermost. So what could I do to get this to work for every instance of the regex in the string?
但所有这一切都取代了“最大”的实例。意味着如果字符串中出现多次GUGU * AGAG,则它仅匹配最外层。那么我该怎么做才能让字符串中的正则表达式的每个实例都能正常工作呢?
1 个解决方案
#1
0
Use a reluctant rather than a greedy quantifier (see the documentation):
使用不情愿而不是贪婪的量词(参见文档):
String s = "hello GUGU hello AGAG hello GUGU hello AGAG";
// greedy
System.out.println(s.replaceAll("GUGU(.*)AGAG", ""));
// prints "hello "
// reluctant
System.out.println(s.replaceAll("GUGU(.*?)AGAG", ""));
// prints "hello hello "
#1
0
Use a reluctant rather than a greedy quantifier (see the documentation):
使用不情愿而不是贪婪的量词(参见文档):
String s = "hello GUGU hello AGAG hello GUGU hello AGAG";
// greedy
System.out.println(s.replaceAll("GUGU(.*)AGAG", ""));
// prints "hello "
// reluctant
System.out.println(s.replaceAll("GUGU(.*?)AGAG", ""));
// prints "hello hello "