By the looks of it {he thinks} he knows what he’s doing.

Regex Love

I have been doing some regular expression work in JavaScript the past couple of days, and I realize regular expressions can be powerful and do a lot for me. The following examples are variations (not the actual because I could get in trouble here at work) of what I was able to do off the top of my head:

/^p\d{3}$/ // looks for a “p” followed by 3 digits
/^\d{6}(-\d{6})?$/ // looks for 6 digits with an optional dash then 6 more digits

Just thought I’d share in my own joy. Can you see the joy in those regex? Love it.

Note: I fixed the second example per Mitch’s bug find. Apparently my transcription from my whiteboard was not perfect. :-)

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Comments on: "Regex Love" (1)

  1. Regular expressions are cool (fun?)! I use them quite often. A bit of a learning curve, but once you get the hang of it not too difficult. Using sed and regex you can do some absolutely amazing things!

    BTW. You need the ‘?’ quantifier after the ‘-’ in your 2nd example to make ‘-’ optional… or after ‘(‘ and ‘)’ to make both the ‘-’ and the trailing six digits optional. Like this:

    /\d{6}-?\d{6}/ # matches ’123456654321′ or ’123456-654321
    /\d{6}(-\d{6})?/ # matches ’123456′ or ’123456-654321′

Leave a comment for: "Regex Love"

You must be logged in to post a comment.