RegEx to compare two substrings within a line

Viewed 48

I have a consistently formatted lines that are essentially delimited field/value pairs and I need to use a single regex expression to compare the values of two fields and match if they are the same. I don't need the values, just the match/no match comparison. Here are two examples, the first should match the second should not.

  1. @@field1@@someValue@@field2@@someValue@@otherField@@otherValue
  2. @@field1@@someValue@@field2@@someDIFFERENTValue@@otherField@@otherValue

I can match any field or value on a known pattern, and I can use lookarounds to do AND operations.

But I don't know how to extract and save the value of some pattern match, like field1@@(.*?)@@

, and then use that "someValue" in an expression comparing it to the "contents" of field2@@(.*?)@@

Thanks in advance for any assistance.

1 Answers

You may use

@@field1@@([^@]*)@@field2@@(?=\1@@)
@@field1@@((?:(?!@@).)*?)@@field2@@(?=\1@@)

Use the former if there can be no @ in value contents. Else, use the latter regex.

See the regex demo

Details

  • @@field1@@ - a literal string
  • ([^@]*) - Capturing group 1 (later in the pattern, it can be referred to with \1 backreference): any 0 or more chars other than @
  • @@field2@@ - a literal string
  • (?=\1@@) - immediately to the right of the current location, there must be the same value as captured in Group 1 followed with @@. If end of string can occur, replace with (?=\1(?:@@|$)).

The (?:(?!@@).)*? pattern "roughly" means any text but @@, it actually matches any single char (other than a line break char), as few occurrences as possible, that does not start a @@ char sequence.

Related