I am new to regex and I am trying to come up with something that will match a text like below:
ABC: (z) jan 02 1999 \n
Notes:
- text will always begin with "ABC:"
- there may be zero, one or more spaces between ':' and (z).
- Variations of (z) also possible - (zz), (zzzzzz).. etc but always a non-digit character enclosed in "()"
- there may be zero,one or more spaces between (z) and jan
- jan could be jan, january, etc
- date couldbe in any format and may/may not contain other text as part of it so I would really like to know if there is a regex I can use to capture anything and everything that is found between '(z)' and '\n'
Any help is greatly appreciated! Thank you
23 Answers
The following should work:
ABC: *\([a-zA-Z]+\) *(.+)Explanation:
ABC: # match literal characters 'ABC:' * # zero or more spaces
\([a-zA-Z]+\) # one or more letters inside of parentheses * # zero or more spaces
(.+) # capture one or more of any character (except newlines)To get your desired grouping based on the comments below, you can use the following:
(ABC:) *(\([a-zA-Z]+\).+) 4 Without knowing the exact regex implementation you're making use of, I can only give general advice. (The syntax I will be perl as that's what I know, some languages will require tweaking)
Looking at ABC: (z) jan 02 1999 \n
The first thing to match is ABC: So using our regex is
/ABC:/You say ABC is always at the start of the string so
/^ABC/will ensure that ABC is at the start of the string.You can match spaces with the
\s(note the case) directive. With all directives you can match one or more with+(or 0 or more with*)You need to escape the usage of
(and)as it's a reserved character. so\(\)You can match any non space or newline character with
.You can match anything at all with
.*but you need to be careful you're not too greedy and capture everything.
So in order to capture what you've asked. I would use /^ABC:\s*\(.+?\)\s*(.+)$/
Which I read as:
Begins with ABC:
May have some spaces
has (
has some characters
has )
may have some spaces
then capture everything until the end of the line (which is
$).
I highly recommend keeping a copy of the following laying about
0This should fulfill your requirements.
ABC:\s*(\(\D+\)\s*.*?)\\n
Here it is with some tests
Futher reading on regular expressions:
3