Slashdot Mirror


(Useful) Stupid Regex Tricks?

careysb writes to mention that in the same vein as '*nix tricks' and 'VIM tricks', it would be nice to see one on regular expressions and the programs that use them. What amazingly cool tricks have people discovered with respect to regular expressions in everyday life as a developer or power user?"

9 of 516 comments (clear)

  1. IP and Hardware addresses by rallymatte · · Score: 5, Insightful

    To filter a string to make sure it's a valid ip address this regexp is quite useful.
    /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/

    And this one for mac addresses
    /^[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}$/

    1. Re:IP and Hardware addresses by Richard_J_N · · Score: 5, Informative

      Of course, you can do better still. For mac addresses, try:
          ^([[:xdigit:]]{2}:){5}[[:xdigit:]]{2}$
      [:xdigit:] is short for hexadecimal digits, i.e. a-fA-F0-9
      We can also loop 5 times over the 'XX:' sections.

    2. Re:IP and Hardware addresses by Speare · · Score: 5, Informative

      For pretty much any useful stock problem solved by regular expressions, see Perl's Regex::Common module. A lot of these patterns are fiendishly complicated to deal with edge-cases properly.

      --
      [ .sig file not found ]
    3. Re:IP and Hardware addresses by rallymatte · · Score: 5, Funny

      Not only are you showing off with a lower member id than me, do you also have to come up with a cooler regexp than me?

  2. New Slashot Section by Frankie70 · · Score: 5, Interesting

    Maybe we should have a new section for "Useful Stupid Tricks" on Slashdot.

  3. Regexp-based address validation by mutende · · Score: 5, Informative

    Beautiful regexp that validates RFC 822 addresses: Mail-RFC822-Address.html

    --
    Unselfish actions pay back better
  4. Re:How about by Anonymous Coward · · Score: 5, Interesting

    I actually like these. Nice little highly enriched concentrations of geekery on a single page. Think how long it might take to round up the sort of stuff that appears here by Googling.

    Turing word: insipid
    In a sentence: You find this page insipid but I find it inspiring.

  5. Regex Bill by Anonymous Coward · · Score: 5, Funny

    Why couldn't Bill try out his regular expressions?

    His mom wouldn't let him play with matches.

  6. Do these questions really belong here? by DerCed · · Score: 5, Informative

    I wonder why such FAQs are still posted on a site like Slashdot. We now have a great repository for exactly this kind of questions:
    http://stackoverflow.com/questions/tagged?tagnames=regex&sort=votes&pagesize=15