简体   繁体   English

正则表达式模式以任何顺序匹配字符串

[英]regex pattern to match string in any order

How to find first match of string abc in shuffled order using regex pattern in java?如何使用 java 中的正则表达式模式以随机顺序查找字符串abc的第一个匹配项?

Example:例子:

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

1st match for input 1: abc baab输入 1 的第一个匹配项: abc baab
1st match for input 2: b cba aab输入 2 的第一个匹配项:b cba aab
1st match for input 3: bca aabc输入 3 的第一个匹配项: bca aabc

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.上述 2 种模式匹配 3 个连续字符,包括重复值。
example: aba bac例子: aba bac
expected: aba bac预期: aba bac

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

This one matches and empty character in-between each character.这个匹配每个字符之间的空字符。 ie, string position (0,0), (1,1), (2,2) etc...即,字符串 position (0,0), (1,1), (2,2) 等...

Have you tried to look of all the possibilities?你有没有尝试过所有的可能性? Something like this with your example:你的例子是这样的:

(abc|acb|bca|bac|cab|cba)

Maybe you should try this regex:也许你应该试试这个正则表达式:

^(?=[\s\S]*(a)+)(?=[\s\S]*(b)+)(?=[\s\S]*(c)+)[\s\S]*$
(?: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.空组的作用类似于复选框,因此如果\1\2\3匹配,则每个字母必须至少出现一次。 Since the regex only consumes three characters, you know there's exactly one of each letter.由于正则表达式仅使用三个字符,因此您知道每个字母只有一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM