jitendra varshney
jitendra varshney

Reputation: 3562

replace specific word using regex except one case

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 ?

Upvotes: 0

Views: 112

Answers (2)

JSS
JSS

Reputation: 2183

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");
    }

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

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|_)"

Upvotes: 2

Related Questions