Get the latest tech news
Demystifying the regular expression that checks if a number is prime (2016)
Ever wondered how the ^.?$|^(..+?)\1+$ regular expression can tell you if a number is not prime? In this blog post you'll learn how and why it works. Code examples in Java, JavaScript, Python and Perl are provided.
The explanation will be programming language agnostic, I will, however, provide Python, JavaScript and Perl versions of the Java code above and explain why they are slightly different. The lie has to do with the order in which the regex engine checks for multiples, it actually starts with the highest number and goes to the lowest, and not how I explain it here. If you remember correctly, I said that due to the peculiarities of the way String.matches works in Java, the regular expression that matches non-prime numbers is not the one in the code example above (.?|(..+?
Or read this on Hacker News