1

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

  • If the string has a locale (_en or _ja) at the end, add _exact before the locale.
  • If _exact is already present, don't add it again.
  • If no locale at the end, and no exact, add _exact at the end of the string.

E.g.:

  • something -> something_exact
  • something_en -> something_exact_en
  • something_ja -> something_exact_ja
  • something_exact_en -> something_exact_en
  • 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. 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!

3
  • 3
    Try regex101.com/r/tm0esC/1 Commented Nov 13, 2017 at 8:43
  • @WiktorStribiżew Your regex seems to be working with all the strings I have. I will accept your answer if you post the regex in the answer section. Thank you! Commented Nov 13, 2017 at 8:54
  • 1
    anubhava's regex is almost the same, a tiny bit optimized. Just .+? matches 1 or more chars , and I used .*?, 0 or more chars at the start. Commented Nov 13, 2017 at 8:56

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

2 Comments

This works! But Wiktor's regex also works, and since he answered first, I would accept his answer. Unless you find an issue with it? Thank you for your answer as well!
I just checked Wiktor's regex. No I don't find any issue with that as both regex are almost similar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.