1
public static boolean isPrime(int n) {
    return !new String(new char[n]).matches(".?|(..+?)\\1+");
}

https://stackoverflow.com/posts/4515687/revisions

What is this doing in detail?

Is ".?|(..+?)\\1+" equal to ".?" ?

( I'm practising regex from this website http://regex101.com/r/jL7qD4 )

Community
  • 1
  • 1
Beeno Tung
  • 1,058
  • 10
  • 17
  • Did you see the [comments](http://stackoverflow.com/questions/2385909/what-would-be-the-fastest-method-to-test-for-primality-in-java/4515687#comment14255500_4515687)? – p.s.w.g May 13 '14 at 22:06
  • 1
    Did you see the explanation on the right side in regex101.com, it has explained in detail. – BMW May 13 '14 at 22:08
  • Your title has nothing to do with your actual question. – Nic Jun 20 '16 at 21:45

1 Answers1

0

OK, so let's break it down:

.? optionally matches any single character. So this statement will match the empty string or any single character.

a|b in regex-speak is different options - it'll match either a or b.

The last clause, (..+?)\\1+, does the following:

. matches any single character.

.+? matches one or more characters, non-greedily.

\\1+ matches the contents of the capture group (the bit in brackets) one or more times.

So, to put it simply, no, .?|(..+?)\\1+ is not the same as .?, but is instead a superset (it will match everything .? will, and more).

Sebastian Lenartowicz
  • 4,695
  • 4
  • 28
  • 39