0

i have three string app, app_abc, appabc i want to replace any of the string with code (for replacing) output should be

  • app -> code,
  • app_abc -> code_abc,
  • appabc -> appabc

i have tried this replaceAll("^app", code); but it will be replaced starting app

wrong output:

  • app -> code,
  • app_abc -> code_abc,
  • appabc -> codeabc(i want to exclude this type of string using regex)

i know i have to use or oprator so i have tried this

replaceAll("^app|app_(?!(.*))", code);

https://regex101.com/r/Ils9kM/1

but it is wrong i think anyone can suggest ?

14
  • You don't have to use an alternation (the OR operator) nor a lookahead. You need an optional capturing group and word boundaries. Commented Feb 18, 2017 at 12:44
  • can you give example? Commented Feb 18, 2017 at 12:47
  • 1
    Negative lookahead to the rescue: replaceAll("^app(?!abc)", "code") Commented Feb 18, 2017 at 12:50
  • 1
    Can we say that you want to replace app when it is at the beginning of a string but not followed by any letter? Commented Feb 18, 2017 at 12:56
  • 2
    I'd advise replaceAll("\\bapp(?![a-zA-Z])", "code"); or the pattern can also be "\\bapp(?=\\b|_)" Commented Feb 18, 2017 at 12:57

2 Answers 2

2

You want to replace abc only at the start of a word and only when it is not followed with another letter. Use

replaceAll("\\bapp(?![a-zA-Z])", "code")

If you want abc to be followed with a word boundary or underscore, the pattern can also be 

"\\bapp(?=\\b|_)"
Sign up to request clarification or add additional context in comments.

2 Comments

Do you recommend any in-depth Java tutorials on regexes?
Since I'm on a mobile right now, I cannot add more details.@Grzegorz, sorry, I do not know specific Java related regex tutorials, there is regexone.com for JavaScript. A lot can be found at regular-expressions.info.
0

Try this:

public static void main(String []args){
        Assert.assertEquals("code", repl("app"));
        Assert.assertEquals("code_abc",repl("app_abc"));
        Assert.assertEquals("appabc",repl("appabc"));
        Assert.assertEquals("appa_bc",repl("appa_bc"));
        Assert.assertEquals("fooapp",repl("fooapp"));
        Assert.assertEquals("foo_app",repl("foo_app"));
        System.out.println("All Good");
    }

    private static String repl(final String str) {
        return str.replaceAll("\\bapp(?![a-zA-Z])", "code");
    }

Comments

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.