我有一个巨大的字符串,我想与以下正则表达式匹配:
"\\s*<?.*?>\\s*<abc>[\\s\\S]*|\\s*<abc>[\\s\\S]*"
如
myHugeString.matches("\\s*<?.*?>\\s*<abc>[\\s\\S]*|\\s*<abc>[\\s\\S]*"));
该字符串非常大,因此在末尾匹配[\ s \ S] *会占用大量时间。我希望只匹配第一部分
(\\s*<?.*?>\\s*<abc>)
,此后我不在乎。解决这个问题的最有效方法是什么
谢谢
最佳答案
您可以在此处使用Pattern和Matcher类:
通过使用Pattern
编译正则表达式来创建Pattern#compile(regex)
对象。
然后通过使用Matcher
在字符串上应用Pattern
对象来创建Pattern#matcher(CharSequence)
对象。
然后使用Matcher#find()
方法找到您感兴趣的模式。
样例代码:
Pattern pattern = Pattern.compile("\\s*<?.*?>\\s*<abc>|\\s*<abc>");
Matcher matcher = pattern.matcher(yourString);
if (matcher.find()) {
// Pattern found.
}
您甚至可以将正则表达式模式缩短为:
"(?:\\s*<?.*?>)?\\s*<abc>"