简体   繁体   English

使用正则表达式在匹配字符串之前或结尾插入字符串

[英]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。

  • If the string has a locale ( _en or _ja ) at the end, add _exact before the locale. 如果字符串末尾有语言环境( _en_ja ),请在语言环境之前添加_exact。
  • If _exact is already present, don't add it again. 如果_exact已经存在,请不要再添加。
  • If no locale at the end, and no exact, add _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");

RegEx Demo 正则演示

  • (?!.*_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM