I am trying to match below paterns:
A-Test!1.2
A-Test
ATest
A-Test!1.2.3
in below text:
[A-Test!1.2] [xyz] [def]
[A-Test] [xyz] [def]
[ATest] [xyz] [def]
[A-Test!1.2.3] [xyz] [def]
I tried my hand @ regex
[^\[] (\-*\!\d.\d(?:.\d))
But it is only matching one line:
Can you please guide on how to get the matches done for all lines?
CodePudding user response:
Use ? for optional pattern
I assume the difference between the [] boxes is the searched string must start with a capital letter, and the part from ! onwards is optional. You can make something optional with a ? behind it.
You can use this regular expression to find your example texts:
\[([A-Z][A-Za-z0-9-] (![\d.] )?)\]
See here to play around with it:
https://regex101.com/r/5ekTkJ/1
CodePudding user response:
You may spell out all the pattern parts, e.g. like
(?<=\[)[A-Z]-?[A-Za-z] (?:!\d (?:\.\d )*)?(?=])
See the regex demo. Details:
(?<=\[)- a positive lookbehind that requires a[char immediately on the left[A-Z]- an uppercase letter-?- an optional-[A-Za-z]- one or more letters(?:!\d (?:\.\d )*)?- an optional group matching!- a!char\d (?:\.\d )*- one or more digits and then zero or more occurrences of.and one or more digits
(?=])- a positive lookahead that requires a]char immediately on the right.

