Regex ignore part of the string in matches -
suppose have tags object such:
["warn-error-fatal-failure-exception-ok","parsefailure","anothertag","syslog-warn-error-fatal-failure-exception-ok"]
i able use regex match on "failure" exclude "warn-error-fatal-failure-exception-ok".
so in above case if used regex search failure should match failure on parsefailure , ignore rest.
how can accomplished using regex?
note: regex has exclude whole string "warn-error-fatal-failure-exception-ok"
edit
after documenting answer below, realized maybe looking is:
(?<!warn-error-fatal-)failure(?!-exception-ok)
so i'm adding here in case fits looking better. regex looking "failure" using negative lookbehind , negative lookahead specify "failure" may not preceded "warn-error-fatal-" or followed "-exception-ok".
answer developed comments:
the following regex captures "failure" substring in "parsefailure" tag, , puts in group 1:
^.*"(?![^"]*warn-error-fatal-failure-exception-ok[^"]*)[^"]*(failure)[^"]*".*$
detail
i break regex in parts, , i'll explain each. first, let's forget in between first set of parentheses, , let's @ rest.
^.*"[^"]*(failure)[^"]*".*$
the important part of regex trying capture in group, word "failure" part of tag surrounded double-quotes. regular expression above matches whole test string, focuses on tag surrounded double-quotes , containing substring "failure".
^.*"
matches character beginning of string quote
"[^"]*(failure)[^"]*"
matches tag surrounded double-quotes , containing substring "failure". literally: double-quote, followed 0 or more characters not double-quotes, followed "failure", followed 0 or more characters not double-quotes, followed double-quote. parentheses capture word "failure" in group 1.
".*$
matches character double-quote end of test string
because [^"]*(failure)[^"]*
matches tags containing substring "failure", ^.*"[^"]*(failure)[^"]*".*$
capture substring "failure" first tag containing string. in other words, capture "failure" warn-error-fatal-failure-exception-ok
tag not want, exclude warn-error-fatal-failure-exception-ok
tag being possible match tag portion of regex: [^"]*(failure)[^"]*
. achieved negative lookahead:
(?![^"]*warn-error-fatal-failure-exception-ok[^"]*)
this negative lookahead means: "the regular expression following negative lookahead can't match [^"]*warn-error-fatal-failure-exception-ok[^"]*
". (?!
, )
part of syntax. can read more here.
more breakdown
^
matches beginning of test string
.*
matches character 0 or more times
"
matches double-quote character
[^"]*
matches character other double-quote character 0 or more times
(failure)
matches word "failure", , since in parentheses, capture in group; in case, captured in group 1 because there 1 set of capturing parentheses. parentheses of negative lookahead non-capturing.
$
matches end of test string
Comments
Post a Comment