155 points · by Lindrian · 13y ago · 30 comments
They also have a great example:
test string:
Today's date is: 9/28/2013.
regex:
(?<month>\d{1,2})\/(?<day>\d{1,2})\/(?<year>\d{4})
result:
month 9
day 28
year 2013
Screenshot here: http://i.imgur.com/ixyHRde.png(for Python flavor:
https://www.debuggex.com/?flavor=python )
and one more Python + regex:
$ grep -r -n --color "foo*bar" src
If I want to validate input data with the machine I just use a parser.
$mac =~ ^[A-Fa-f0-9]{16}$
Gets the job done. How else, but a regular expression so concisely?And, when you say, "If I want to validate input data with the machine I just use a parser." - that's pretty much what a regex engine is - a sophisticated parser, and the regular expression is the "commands" that you feed to it to parse the input text.
regex_ipv4='^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])$'
Gets the job done.
How else would you do it?
You can then build up a library of these, and use them on other projects.
Taking your question generally, I was curious to see what it might look like as a parser, since I find that regex a little hard to read. Here's an implementation with Haskell's parsec:
def is_ipv4_addr(s):
try:
octets = s.split('.')
assert len(octets) == 4
for o in octets:
assert 0 <= int(o.lstrip(0) or '0') < 256
except:
return False
return True
It is longer; on the other hand, it is easier to read and more importantly easier to verify correctness.import Text.ParserCombinators.ReadP -- or the parser lib of your choice
import Data.Char
...
macP = count 16 (satisfy isHexDigit)
For example if it is ? repeat 1 time, + repeat 2, * repeat 3 etc...
If it is |, choose the first or choose randomly.
After asking a question on the #jetpack channel, members have spotted the mistake: The regex was correct, but it needed to "match the exact string" as mentioned on the doc. I've read it, but didn't understand that point. There was a missing "." at the beginning and the end. So /.regex.*/
Thanks for putting this.
Here is another regex tester: http://www.gethifi.com/tools/regex
If you don't agree with me, could you perhaps suggest an improvement?
Exp (made it wrong in purpose) ^inout\s+\[[0-9]\: It just display "No Matches".
It would be cool if it kind of guide what exp you want to use to match test string. What you put in Test string is what you want to get.