3
votes

Is there any way (or possible) to invert match a pattern (not a pre-given word) using regex?

e.g.

Input string:

a:b, c:d, a:b1,s:sad

The pattern is

a:[^,]+,?

This pattern matches "a:b," and "a:b1," in the string. Could I replace/invert match the remain part, i.e. " c:d," and "s:sad" without using grep -v -e?

e.g. continue, demo output replacing the remain with "[TAG]":

a:b,[TAG], a:b1,[TAG]

The [^pattern] or (?!pattern) trick fails and grep with -e -v options are not allowed here.

Thanks!

2
You could write another regex which captures the other strings, i.e. [^a]:[^,]+,? - pzelasko

2 Answers

1
votes

The expression

/((a:[^,]+,?\s?)(((?!a:[^,]+).)+(,|$))+)/\2[TAG]\5/g

will replace

a:b, c:d, a:b1,s:sad

with

a:b, [TAG], a:b1,[TAG]

But I'm not sure I understood your comment about (?!pattern) not working. I am testing at https://regex101.com/.

0
votes
[^,:]+(?<!\ba):[^,]+,?

You can simply use this with grep -P .See demo.

https://regex101.com/r/hE4jH0/25