Home > Blockchain >  Regex that excludes character in one line but not another
Regex that excludes character in one line but not another

Time:01-31

I have the following two lines for which I'm trying to create an expression:

Auth.NAS-IP-Address=0.0.0.0,

auth.Alerts=Failed to construct filter=select COALESCE('%{Endpoint:intel_endpoint_BLOCK_locations}','none') ilike '%;' || '%{Device:Location}' || ';%' as is_blocked.

I am trying to create a capture group that captures everything after the first '=' in each line. (Everything after "Address=" and "Alerts="). However, I'd like to exclude the ',' at the end of the first line.

This is the closest I've come:

^([\S] )=(. )(,$)?

My goal here was to capture everything except for a comma that occurs right before the end of the line. That didn't work.

The following expression will exclude the ',' on the first line, but also stops the capture group at the comma in the second line and therefore doesn't capture the entire value.

^([\S] )=(. ),

Is this something that's even possible with Regex? Can I create an expression that will exclude a character on one line but not another?

CodePudding user response:

You can try make the second group non-greedy:

^(\S )=(. ?),?$

Regex demo.

CodePudding user response:

As I understand, in the first line you wish to capture everything after the first equals sign, except for a comma at the end of that line; in all other lines you wish to capture everything after the first equals sign, regardless of whether the line ends with a comma. You can do that with the following regular expression.

(?:\A(\S )=(. ),$|^(?!\A)(\S )=(. ))

Demo

The regular expression can be broken down as follows.

(?:      # begin non-capture group
  \A     # match beginning of the string
  (\S )  # match >= 1 non-whitespace chars, save to group 1
  =      # match equals sign
  (. )   # match >= 1 chars other than line terminators, save to group 2
  ,      # match a comma
  $      # match end of line
|        # or
  ^      # match beginning of a line
  (?!\A) # assert location is not at the beginning of the string
  (\S )  # match >= 1 non-whitespace chars, save to group 3
  =      # match equals sign
  (. )   # match >= 1 chars other than line terminators, save to group 4 
)        # end non-capture group

(?!\A) is a negative lookahead. One could alternatively use the negative lookbehind (?<!\A).

  • Related