3 ms·
> RE patterns can be horribly ugly It worth to be noted that the verbose flag (re.X or re.VERBOSE in Python) may help to get more readable/friendly regexes (by
by alexis-d 15y ago
> RE patterns can be horribly ugly
It worth to be noted that the verbose flag (re.X or re.VERBOSE in Python) may help to get more readable/friendly regexes (by allowing whitespace and comments).
- ajross 15y agoI'm desperately fighting the urge to snark: but another very effective treatment for dealing with unreadable regex syntax is to learn regex syntax. In my experience probably 90% of people who complain about regular expressions simply don't know them very well. It's a declarative language without symbols or recursion: that means that it's just not well-suited to being "broken down and simplified". You just have to bite the bullet and learn it. With a little practice, the basic features (e.g. beginning/end of line markers, character classes and captures, maybe non-capturing parentheses too) should be readable without trouble.
- alexis-d 15y agoI think you missed my point. I agree that for trivial regex it's useless. For instance (directly taken from Python doc) in this case: a = re.compile(r"""\d + # the integral part \. # the decimal point \d * # some fractional digits""", re.X) b = re.compile(r"\d+\.\d*") that's useless. But for more complex problems it may be useful (e.g. http://www.doughellmann.com/PyMOTW/re/ http://www.doughellmann.com/PyMOTW/re/ I know email matching regexes are not really complex or even a good example of use of regexes but that's the first example I found). Another point is that even if I can read/write (that's the case) regexes other people may have to deal with my code and it's a well known fact that many people doesn't understand/like regex, so splitting them in small "chunks" may help them.
- ajross 15y agoTo be fair: my argument wasn't against the use of the /x suffix to a regex. I'm sure that there are circumstances in the wild (though quite honestly I can't recall seeing any in production code, and I've written and read a truckload of regexes over the years) where it's used productively to document a really hairy expression. I'm just saying that 90% of the time when users complain about not being able to read a regex, the solution should be "hit the books" not "rewrite the expression".