使用正则表达式的Java模式匹配
发布时间:2020-12-14 02:29:24 所属栏目:百科 来源:网络整理
导读:我有一个Long字符串,我必须解析不同的关键字.例如,我有字符串: "==References== This is a reference ==Further reading== *{{cite book|editor1-last=Lukes|editor1-first=Steven|editor2-last=Carrithers|}} * ==External links==" 我的关键字是 '==Refer
我有一个Long字符串,我必须解析不同的关键字.例如,我有字符串:
"==References== This is a reference ==Further reading== *{{cite book|editor1-last=Lukes|editor1-first=Steven|editor2-last=Carrithers|}} * ==External links==" 我的关键字是 '==References==' '==External links==' '==Further reading==' 我已经尝试了很多正则表达式的组合,但我无法恢复所有的字符串. 我试过的代码: Pattern pattern = Pattern.compile("=+[A-Za-z]=+"); Matcher matcher = pattern.matcher(textBuffer.toString()); while (matcher.find()) { System.out.println(matcher.group(0)); }
你不需要逃避=符号.而且你还应该在角色类中包含一个空格.
除此之外,您还需要在角色类上使用量词来匹配多次出现.试试这个正则表达式: Pattern pattern = Pattern.compile("=+[A-Za-z ]+=+"); 您还可以通过使用增加灵活性来接受两个==之间的任何字符. ? (你需要不情愿的量词来阻止它匹配所有东西,直到最后一个==)或[^ =]: Pattern pattern = Pattern.compile("=+[^=]+=+"); 如果双方的=的数量相同,那么您需要修改正则表达式以使用捕获组和反向引用: "(=+)[^=]+1" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |