我有一个符合下列模式的字符串部分。
的 ABCD |(| A | AB | ABC)E(FGHI |(| F | FG | FGH)jklmn)
但我遇到的问题是,我的整个字符串是重复上述类似模式的组合。我的整个字符串必须包含超过14套以上的图案
任何人都可以帮我改进上面的RegEx到想要的格式。
谢谢
的更新
输入示例:
匹配的字符串部分:abcd,abefgjkln,efjkln,ejkln
但整个字符串是:abcdabefgjklnefjklnejkln(以上4个部分的组合)
整个弦中必须有超过15个部分。上面只有4个部分。所以,这是错的。
答案 0 :(得分:5)
这将尝试在字符串中至少匹配您的“部分”15次。
boolean foundMatch = false;
try {
foundMatch = subjectString.matches("(?:(?:ab(?:cd|efgjkln))|(?:(?:ef?jkln))){15,}");
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
如果上述任何部分至少重复15次,则发现匹配将为真,否则它将保持为假。
细分:
"(?:" + // Match the regular expression below
"|" + // Match either the regular expression below (attempting the next alternative only if this one fails)
"(?:" + // Match the regular expression below
"ab" + // Match the characters “ab” literally
"(?:" + // Match the regular expression below
// Match either the regular expression below (attempting the next alternative only if this one fails)
"cd" + // Match the characters “cd” literally
"|" + // Or match regular expression number 2 below (the entire group fails if this one fails to match)
"efgjkln" + // Match the characters “efgjkln” literally
")" +
")" +
"|" + // Or match regular expression number 2 below (the entire group fails if this one fails to match)
"(?:" + // Match the regular expression below
"(?:" + // Match the regular expression below
"e" + // Match the character “e” literally
"f" + // Match the character “f” literally
"?" + // Between zero and one times, as many times as possible, giving back as needed (greedy)
"jkln" + // Match the characters “jkln” literally
")" +
")" +
"){15,}" // Between 15 and unlimited times, as many times as possible, giving back as needed (greedy)
答案 1 :(得分:1)
这个怎么样:
(?:a(?:b(?:c(?:d)?)?)?ef(?:g(?:h(?:i)?)?)?jklmn){15,}
说明:你创建了一个非捕获组(带有(?: ... )
),并说这应该重复> = 15次,最后是花括号。
答案 2 :(得分:-1)
首先,您的模式似乎可以简化。真正模式a
是ab
的子集,是abc
的子集,因此如果模式abc
匹配则意味着a
也匹配。考虑一下并适当地改变你的模式。现在它可能不是你真正想要的。
其次,重复某事是使用{N}
,即abc{5}
表示“abc
重复五次”。您还可以使用{3,},{,5},{3,5}表示重复> = 3,重复< = 5,3< = repeat< = 5。