1

With a collection of string as so:

string s1 = "   Identifier1 = Value1                      ## Comment";
string s2 = "   Something = SomeData";
string s3 = "   Name = information\\t\\t\\t## More comments!";
string s4 = "   Nam2 = information";

I need a regex pattern that will grab all of the information on the line after the equals-sign (=) up to either the end of the line OR the ## comment marker, but NOT capture either of them.

Giving me (respectively):

" Value1                      "
" SomeData"
" information\\t\\t\\t"
" information"

I've come up with this so far: (?<=[=]).+(?=(?>##|$))

It kind of works, insofar as it manages to grab all text after the = sign until the end of the string, but it never works when there's a comment marker: ## as it still grabs until the end of the string, instead of stopping at the ##.

...and if I change the pattern to: (?<=[=]).+(?=##))

Then it only works on lines with comment markers (and stops before them as desired).

So what am I doing wrong/missing to get it to end the capture either just before ## OR at EOL? Also, I can't use explicit or implicit capturing groups as these patterns are passed into a parser that turns them into non-capturing groups when it processes them.

I've never used look-ahead/behind patterns until just the past few days and this stuff is breaking my brain...

NetXpert
  • 388
  • 3
  • 12

2 Answers2

2

You can use this regex (as seen in use here):

(?<==)(?:(?!#{2}).)*
  • (?<==) lookbehind ensuring what precedes matches = literally
  • (?:(?!#{2}).)* matches any character (excludes newline) any number of times until it reaches ##
ctwheels
  • 19,377
  • 6
  • 29
  • 60
  • Okay, well, it definitely works! Though I'm still trying to work out how/why! (Also, thanks for the link! Now that I know what it's called, I'm actually finding assistance references about it. Without knowing that term I was totally hitting brick walls trying to search for a sol'n!) – NetXpert Apr 03 '19 at 19:13
1

You can use this regex,

(?<==).*?(?=#{2}|$)

Explanation:

  • (?<==) - Positive look behind to ensure matched text is preceded by =
  • .*? - This matches any text in non-greedy way
  • (?=#{2}|$) - Positive look ahead to ensure matched text is followed by either ## or end of line $

Demo

Pushpesh Kumar Rajwanshi
  • 17,850
  • 2
  • 16
  • 35