r/linux • • Apr 24 '11

Regular Expressions Cheat Sheet (V2)

http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/
78 Upvotes

13 comments sorted by

6

u/broken_cogwheel Apr 24 '11

If you use that example email pattern for validation: I hate you.

3

u/[deleted] Apr 24 '11
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

Really though, one regex for email validation is pretty thick...

3

u/broken_cogwheel Apr 24 '11

There is no perfect email validation regex. It would be better to split it up and check the portions of the address separately and be RFC compliant. If not, I'd rather accept invalid addresses rather than turn away valid ones.

w/e.

1

u/[deleted] Apr 25 '11

That is a cut and paste from RFC 2822. Unfortunately, it sucks.

2

u/geniusfreak Apr 25 '11

I see your regex, and raise you this one.

2

u/DaveChild Apr 25 '11

Yes, sorry about that. The sample patterns were intended to be demonstrations of some ways of using regexes, rather than real-world usable patterns. Most useful patterns are far too long to use as a sample (as you can see from Skunkleton's example). I do intend to improve the sample patterns, though, so if you have any suggestions for better ones, please feel free to suggest them.

2

u/andey Apr 25 '11

huge find my friend, i'm comfortable writing regular expressions, but this will help when writing those tricky expressions

1

u/jdpage Apr 24 '11

For anyone wondering, this is appropriate for Perl, PCRE, Ruby, and Tcl ARE. It is not generally appropriate for BRE, ERE, and GNU, because they are relatively fail and don't support some stuff, or ed/ex/vi/vim/sed/grep RE, where different characters have to be escaped, and don't support the same character classes (or shorthands).

4

u/[deleted] Apr 24 '11

And just in case anyone is irritated by GNU grep, check out the -P flag, which makes things much better :)

1

u/jdpage Apr 24 '11

It's great, I use it for anything more complex than a simple wildcard match. It turns it into a nice little frontend to PCRE.

1

u/driver8 Apr 24 '11

The sample patterns are pretty silly (by which I mean bad). And I've never seen angle brackets (< and >) used as a metacharacter in regular expressions. What implementation does this?

2

u/DaveChild Apr 25 '11

The samples were so people could see how the various parts can fit together, rather than patterns people could take and use. They do need to be fixed (or replaced) so please do feel free to suggest improvements.

The tricky bit is getting a useful pattern into only a few characters that people may be able to relate to when they are just getting started with regex patterns. I figured PHP devs would be most likely to find this cheat sheet, hence the web-focus to the samples.