Reputation: 309
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:
orkey_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+)
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.
Upvotes: 1
Views: 1046
Reputation: 626870
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 ((?:...)
).
Upvotes: 1