Regex lookahead / lookbehind comments

I have a fragment of a configuration file that should match the specified contents of a line string, but only when they are not commented out, here is my current regular expression:

(?<!=#)test\.this\.regex\s+\"(.*?)\"

I feel this should work? I read it as follows:

(?<!=#) lookbehind to make sure it is not preceded #

test\.this\.regex\s+\"(.*?)\" corresponds to test.this.regex "sup1"

Here is a fragment of the configuration

    test.this.regex "sup1" hi |sup1| # test.this.regex "sup3" hi |sup3|
# test.this.regex "sup2" do |sup2|
    test.this.regex "sup2" do |sup2|

But my regex matches all 4 times:

Match 1
1.  sup1
Match 2
1.  sup3
Match 3
1.  sup2
Match 4
1.  sup2
+4
source share
2 answers

You can use this PCRE regular expression:

/(?># *(*SKIP)(*FAIL)|(?:^|\s))test\.this\.regex\s+\"[^"]*\"/

Working demo

  • (*FAIL) behaves like an unsuccessful negative statement and is synonymous with (?!)
  • (*SKIP) , ,
  • (*SKIP)(*FAIL) , lookbehinf .

UPDATE: , ruby โ€‹โ€‹ (*SKIP)(*FAIL), :

(?:# *test\.this\.regex\s+\"[^"]*\"|\b(test\.this\.regex\s+\"[^"]*\"))

# 1.

2

0

( ), String # split regex less lookbehind?

def doit(str)
  r = /test\.this\.regex\s+\"(.*?)\"/
  str.split('#').first[r,1]
end

doit('test.this.regex "sup1" hi |sup1| # test.this.regex "sup3" hi |sup3|')
  #=> "sup1"
doit('# test.this.regex "sup2" do |sup2|')
  #=> nil
doit('test.this.regex "sup2" do |sup2|')
  #=> "sup2"
0

Source: https://habr.com/ru/post/1540936/


All Articles