我使用 StringBuilder 创建一个正则表达式,它匹配包含字符串中所有字符的任何字符串(或者我认为是这样)。
StringBuilder myRegex = new StringBuilder("");
for (char c: myCharArray) {
myRegex.append(String.format("?=.*%c", c));
}
我相信这应该匹配以下类型的字符串:
char [] myCharArray = {'a', 's', 'e'};
String fruits = "Apples Bananas and Grapes";
但我收到以下错误:
java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0 ?=.*a?=.*s?=.*e
最佳答案
我猜,你正在尝试构建,
(?=.*a)(?=.*s)(?=.*e)
完整表达,
^(?=.*s)(?=.*e)(?=.*a).*$
其中,
myRegex.append(String.format("(?=.*%c)", c));
可能部分有效。
<小时/>话虽如此,对每个字符进行积极的前瞻并不是真正高效,也不是最好的想法,因为每个字符的时间复杂度都是 O(N)。
<小时/>如果您想简化/修改/探索表达式,regex101.com 的右上角面板已对此进行了解释。 。如果您愿意,也可以在 this link 观看,它如何与一些示例输入相匹配。
<小时/>测试
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "^(?=.*s)(?=.*e)(?=.*a).*$";
final String string = "Apples Bananas and Grapes\n"
+ "Some String that doeS not have A lower S or E or A";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
}
}
}
输出
Full match: Apples Bananas and Grapes
关于java - 如何构建一个正则表达式来匹配包含子字符串中所有字符的任何字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58792929/