Search code examples
regexcfengine

How to match a character in the middle of the string with known but variable size prefix


To be more specific, there is a line (among other lines in a given string):

sudo:x:27:foo,bar,baz
         ^---we need to match this character

The prefix is known, and can be expressed as ^sudo:x:\d+

The problem: positive lookbehind assertion must be of a fixed size, otherwise I would use (?<=sudo:x:\d+)

The question: how to match that exact colon (and it must be the only matched character)

Playground: http://regex101.com/r/gG9vW6/2

PS: For those who are curious why I need that:

This is just a part of the bigger task, which could be expressed as: add a user to the sudo group if it is not there yet with the following parser limitations (it comes from the software being used, cannot be changed):

  • You can only perform replace operation, so you need to match any character
  • It is technically impossible to use the regex (matches) and references in the replacement string

UPDATE

There is a way to use the (matches), so it's not a problem anymore :-)

This is how to refer to the matches in cfengine:

$(match.N)

where N is the index of the capturing group.

See: https://docs.cfengine.com/docs/3.5/manuals-language-concepts-pattern-matching-and-referencing.html


Solution

  • (?=^sudo:x:\d+:.*$)(.*):
    

    You can try this.

    Replace with:

    $(match.1)<your char>
    

    See demo for equivalent version in PCRE.