简体   繁体   中英

pcre_regex with conditional patterns, "or" and "and" conditions

Am using a pcre-regex-engine to match pattern from my file/line. The lines am trying to find a match are:

line-001 key_one:10.20.30.40 any data goes here
line-002 key_two:11.22.33.44 any data goes here
line-003 key_off:12.32.42.52 any data goes here
line-004 key_ten:34.45.67.89 any data goes here

Now, I want to match ip patterns starting with key_one: , key_two: or key_ten: . I need my pattern to be conditional,"match any ip pattern starting with key_one: or, key_two: or key_ten: .

expected pattern= key_one | key_two| key_ten & (\\d+.\\d+.\\d+.\\d+) key_one | key_two| key_ten & (\\d+.\\d+.\\d+.\\d+)

But, The or(|) condition works for pcre,but not the and(&) condition. can some one help me out to use the and (&) condition? thank u.

Your regex is almost correct: you did not consider that the spaces in the pattern are meaningful (in PCRE, outside the character classes) unless /x modifier is used, and that there is a colon between the values. Also, a dot must be escaped to match a literal dot.

You may use

(key_(?:one|two|ten)):(\d{1,3}(?:\.\d{1,3}){3})

that is a contracted form of

(key_one|key_two|key_ten):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})

See the regex demo

If you need to get the IP as a match value, use \\K operator to discard all the text matched up to that operator and return only what is matched later:

key_(?:one|two|ten):\K\d{1,3}(?:\.\d{1,3}){3}

See this regex demo .

Note that it is best practice to write the alternatives in such a way that none of them could match at the same location (to improve performance), that is why it is not a good idea to repeat the same key_ substring within the (...|...) .

The + quantifier matches 1 or more occurrences and in IP addresses there can only be one to three digits, that is why a limiting quantifier {1,3} seems more reliable.

Also, to avoid unnecessary captures, just turn capturing ( (...) ) groups into non-capturing ones ( (?:...) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM