by helloTree · 13y ago · 0 comments
$ 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. 1. 12 .13. 14
089.23.45.67
Both match that? (Your general point is made though - RegExes look fine to the person that just crafted them, but are opaque to the casual observer)import Text.ParserCombinators.ReadP -- or the parser lib of your choice
import Data.Char
...
macP = count 16 (satisfy isHexDigit)