[英]Java Regex Everything Before and Including Match
I need the regex expression to remove any text before a match and including the match 我需要正则表达式来删除匹配前的任何文本并包括匹配
eg. 例如。 I want to remove "123S" and everything before it, I know I can do this with 我想删除“123S”及其前面的所有内容,我知道我可以使用它
string.replaceAll("^.*?(?=[123S])","");
string.replaceAll("123S","");
But really want to do it in a single expression (can't find another example anywhere!) 但是真的想在一个表达式中做到这一点(在任何地方找不到另一个例子!)
You can do it with: 你可以这样做:
string.replaceAll("^.*123S","");
Remove non-greedy ?
删除非贪心?
to match last occurence and .*
everything before. 匹配最后一次出现和.*
之前的一切。
You don't need the look ahead: 你不需要前瞻:
"abc123Sdef123Sxyz".replaceAll("^.*?123S","");
This replaces the first occurence only, if that is what you need (output is def123Sxyz
). 如果这是你需要的(输出是def123Sxyz
),它只替换第一次 def123Sxyz
。
In case you want to replace up to the last 123S, just remove the ?
如果你想要更换到最后的123S,只需删除?
modifier: 修改:
"abc123Sdef123Sxyz".replaceAll("^.*123S","");
Output is xyz
. 输出是xyz
。
string.replaceAll("^.*?123S", "");
(?=
是你不想要的“if follow by”模式,而[123S]甚至不正确它只会捕获'2'。
string.replaceAll("^.*?123S","");
提高效率,提高清晰度,让别人知道你在做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.