-3

How to find first match of string abc in shuffled order using regex pattern in java?

Example:

input 1: abcbaa
input 2: bcbaaa
input 3: cbaaab

1st match for input 1 : abcbaab
1st match for input 2 : bcbaaab
1st match for input 3 : bcaaabc

Patterns that I've tried that didn't work:

(?:([abc])(?!\\.*]\\1)){3}
(?!(.)\\1)[abc]{3}

The above 2 patterns matches 3 consecutive characters, including duplicate values.
example: ababac
expected: ababac

(?=.*[abc])(?=.*[abc])(?=.*[abc])

This one matches and empty character in-between each character. i.e., string position (0,0), (1,1), (2,2) etc...

Arun
  • 125
  • 1
  • 1
  • 7

3 Answers3

1

Have you tried to look of all the possibilities? Something like this with your example:

(abc|acb|bca|bac|cab|cba)
RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
Reda Bourial
  • 329
  • 2
  • 9
1

Maybe you should try this regex:

^(?=[\s\S]*(a)+)(?=[\s\S]*(b)+)(?=[\s\S]*(c)+)[\s\S]*$
The Anh Nguyen
  • 748
  • 2
  • 11
  • 27
  • 1
    `(.|\s)*` is [extremely inefficient](http://stackoverflow.com/questions/2407870/javascript-regex-hangs-using-v8) and should never be used. Instead, use Java's `DOTALL` flag, or add `(?s)` to the beginning of the regex. – Alan Moore Nov 04 '16 at 08:40
  • Thank you, Alan. Can I use [^]* instead of (.|\s)* ? – The Anh Nguyen Nov 04 '16 at 09:57
  • `[^]` is only useful in the JavaScript flavor, which doesn't have a DOTALL option (yet). In Java it's a syntax error. If you are using JavaScript, I recommend you use `[\s\S]` instead. It's longer, but it works the same across flavors, and its meaning is more obvious (any whitespace character + any non-whitespace character = any character). – Alan Moore Nov 04 '16 at 21:10
0
(?:a()|b()|c()){3}\1\2\3

The empty groups act like check boxes, so if \1\2\3 matches, each of the letters must have been seen at least once. Since the regex only consumes three characters, you know there's exactly one of each letter.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156