Pulkit Mittal
Pulkit Mittal

Reputation: 6076

Insert a string before a matching string or at the end using regex

I have a requirement where the string has to contain _exact. I am using Java.

E.g.:

I spent some time and came up with 2 regex that, if ran in succession on the same string, make it possible. 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!

Upvotes: 1

Views: 364

Answers (1)

anubhava
anubhava

Reputation: 784998

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.

Upvotes: 2

Related Questions