What are good regular expressions?

后端 未结 9 932
我寻月下人不归
我寻月下人不归 2021-02-08 05:00

I have worked for 5 years mainly in java desktop applications accessing Oracle databases and I have never used regular expressions. Now I enter Stack Overflow and I see a lot of

9条回答
  •  北恋
    北恋 (楼主)
    2021-02-08 05:26

    Coolest regular expression ever:

    /^1?$|^(11+?)\1+$/
    

    It tests if a number is prime. And it works!!

    N.B.: to make it work, a bit of set-up is needed; the number that we want to test has to be converted into a string of “1”s first, then we can apply the expression to test if the string does not contain a prime number of “1”s:

    def is_prime(n)
      str = "1" * n
      return str !~ /^1?$|^(11+?)\1+$/ 
    end
    

    There’s a detailled and very approachable explanation over at Avinash Meetoo’s blog.

提交回复
热议问题