[英]Insert a string before a matching string or at the end using regex
I have a requirement where the string has to contain _exact
. 我有一个字符串必须包含
_exact
。 I am using Java. 我正在使用Java。
_en
or _ja
) at the end, add _exact before the locale. _en
或_ja
),请在语言环境之前添加_exact。 _exact
is already present, don't add it again. _exact
已经存在,请不要再添加。 _exact
at the end of the string. _exact
。 Eg: 例如:
something
-> something_exact
something
-> something_exact
something_en
-> something_exact_en
something_en
> something_exact_en
something_ja
-> something_exact_ja
something_ja
> something_exact_ja
something_exact_en
-> something_exact_en
something_exact_en
> something_exact_en
something_exact
-> something_exact
something_exact
> something_exact
I spent some time and came up with 2 regex that, if ran in succession on the same string, make it possible. 我花了一些时间,想出了2个正则表达式,如果在同一字符串上连续运行,则有可能。 I am not sure if they cover all the possible cases though.
我不确定它们是否涵盖所有可能的情况。
^(.*)(?<!_exact)(_(?:en|ja))$
^(.*)(?<!_exact)(?<!_(?:en|ja))$
If anybody could help me come up with just 1 regex that does the job, it would be great! 如果有人可以帮我提出一个能完成这项工作的正则表达式,那就太好了! Thank you!
谢谢!
You can use this regex: 您可以使用此正则表达式:
str = str.replaceAll("^(?!.*_exact(?:_en|_ja)?$)(.+?)(_en|_ja)?$", "$1_exact$2");
(?!.*_exact(?:_en|_ja)?$)
is a negative lookahead that skips inputs that ends with _exact
or _exact_en
or _exact_ja
. (?!.*_exact(?:_en|_ja)?$)
是一个否定的超前行为,它会跳过以_exact
或_exact_en
或_exact_ja
结尾的输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.