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:
Any help is greatly appreciated! Thank you
In regular expressions, the period ( . , also called "dot") is the wildcard pattern which matches any single character. Combined with the asterisk operator . * it will match any number of any characters. In this case, the asterisk is also known as the Kleene star.
Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .
The most common wildcards are the asterisk (*), which represents one or more characters and question mark (?) that represents a single character.
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]+\).+)
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 http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With