I need to replace sequences (of various length) of characters by another character. I am working in Eclipse on xml files
For exemple --------
should be replaced by ********
.
The replacement should be done only for sequences of at least 3 characters, not 1 or 2.
It is easy to find the matching sequences in regex for example with -{3,30}
but I don't understand how to specify the replacement sequence.
CodePudding user response:
I made this regex solution ready when question was posted but didn't submit an answer because I kept testing in eclipse and even though regex was working for find
feature, a *
in replacement wasn't changing text in Eclipse editor.
Here is a shorter and a bit more efficient regex:
(?!^)\G-|(?=-{3})-
Replace with a *
CodePudding user response:
You can use
(?:\G(?!\A)|(?<!-)(?=-{3,30}(?!-)))-
See the regex pattern. Details:
(?:\G(?!\A)|(?<!-)(?=-{3,30}(?!-)))
- either\G(?!\A)
- end of the preceding match|
- or(?<!-)(?=-{3,30}(?!-))
- a position that is not immediately preceded with a-
char and is immediately followed with 3 to 30 hyphens (not followed with another hyphen).
-
- a hyphen.
The (?:\G(?!\A)|(?<!-)(?=-{3,30}(?!-)))-
regex goes into the "Find What" filed, *
goes to the "Replace With" field.
Note that regular expressions are only meant to be used in search fields, replacement fields must only contain replacement patterns. Usually, the replacement pattern is a string containing literal string(s) and/or backreferences. Here, we do not need any backreference as the regex does not capture anything.