-1

I am exploring java regex groups and I am trying to replace a string with some characters.

I have a string str = "abXYabcXYZ"; and I am trying to replace all characters except for the pattern group abc in string.

I tried to use str.replaceAll("(^abc)",""), but it did not work. I understand that (abc) will match a group.

Locke
  • 2,041
  • 12
  • 26
Kowcik
  • 49
  • 7
  • `^` means look for `abc` at the beginning of the string. Since the `abc` is not at the start of the string, it is not working. Try removing it. – moys Feb 21 '20 at 03:51
  • @moys If you remove the `^`, then it will replace `abc`, and the goal is to replace anything *but* `abc`. – Andreas Feb 21 '20 at 04:00
  • @Andreas, my bad. I mis-read it – moys Feb 21 '20 at 04:03
  • It has been dealt with many times, see the linked thread and search for *a sequence of characters*.. and then *Other engines allowing lookarounds* – Wiktor Stribiżew Feb 21 '20 at 08:27

2 Answers2

1

It is easier to keep the matching parts of the pattern and concatenate them. In the following example the matcher iterates with find() over str and match the next pattern. In the loop your "abc" pattern will be always found at group(0).

String str = "abXYabcXYZabcxss";
Pattern pattern = Pattern.compile("abc");
StringBuilder sb = new StringBuilder();
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
   sb.append(matcher.group(0));
}
System.out.println(sb.toString());

For only replacing, the nearest you can get would be:

((?!abc).)*

But with the problem that only the a's of abc would not be replaced. Regex101 example

tobsob
  • 688
  • 6
  • 20
  • I understand that this can be achieved in many ways in which yours suggesstion in one. I am purposefully looking for replace in replaceAll using regex and not using pattern – Kowcik Feb 21 '20 at 07:08
  • With regex it is not possible what you want to do I think. Updated my answer. – tobsob Feb 21 '20 at 12:29
0

You might find it easier to find the parts you want to keep and just build a new string. There are flaws with this issue with overlapping patterns, but it will likely be good enough for your use case. However, if your pattern really is as simple as "abc" then you may want to instead consider just counting the total number of matches.

String str = "abXYabcXYZ";
Pattern patternToKeep = Pattern.compile("abc");
MatchResult matches = patternToKeep.matcher(str).toMatchResult();

StringBuilder sb = new StringBuilder();

for (int i = 1; i < matches.groupCount(); i++) {
    sb.append(matches.group(i));
}

System.out.println(sb.toString());
Locke
  • 2,041
  • 12
  • 26