match everything that isn't "hello"

Viewed 85

lets say I have

String str = "sdahasdahellodsadsahdashellodsadsadsahehllo";

and I want to replace every letter that isn't part of hello with the character '_', how would I do it? the output would be something like:

_______hello_________hello_____________

What regex would I have to use? I've used [^hello] but it matches each individual character, not the word itself, so I have a bunch of random letters floating about.

1 Answers

You may replace:

(?:^|\G|(?<=hello))(?!hello).

With:

_

Breakdown:

  • (?: - Start of a non-capturing group.
    • ^ - Match starts at the beginning of the string/line,
    • | - OR...
    • \G - starts immediately following the previous match,
    • | - OR...
    • (?<=hello) - is immediately preceded by "hello".
  • ) - Close the non-capturing group.
  • (?!hello) - Not followed by "hello".
  • . - Any single character (aside from linebreaks).

Regex demo.

Java demo:

String input = "sdahasdahellodsadsahdashellodsadsadsahehllo";
String output = input.replaceAll("(?:^|\\G|(?<=hello))(?!hello).", "_");
System.out.println(output);  // ________hello__________hello_______________

Try it online.

Related