[英]Returning substring without markers using Pattern&Matcher
我想使用Pattern和Matcher将以下字符串作为多个变量返回。
ArrayList <Pattern> pArray = new ArrayList <Pattern>();
pArray.add(Pattern.compile("\\[[0-9]{2}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}\\]"));
pArray.add(Pattern.compile("\\[\\d{1,5}\\]"));
pArray.add(Pattern.compile("\\[[a-zA-Z[^#0-9]]+\\]"));
pArray.add(Pattern.compile("\\[#.+\\]"));
pArray.add(Pattern.compile("\\[[0-9]{10}\\]"));
Matcher iMatcher;
String infoString = "[03/12/13 10:00][30][John Smith][5554215445][#Comment]";
for (int i = 0 ; i < pArray.size() ; i++)
{
//out.println(pArray.get(i).toString());
iMatcher = pArray.get(i).matcher(infoString);
while (dateMatcher.find())
{
String found = iMatcher.group();
out.println(found.substring(1, found.length()-1));
}
}
}
计划产出:
[03/12/13 10:00]
[30]
[John Smith]
[\#Comment]
[5554215445]
我唯一需要的是让程序不打印括号和#字符。 我可以轻松避免使用循环内的子串打印括号,但我无法避免#字符。 #只是字符串中的注释标识符。
这可以在循环内完成吗?
这个怎么样?
public static void main(String[] args) {
String infoString = "[03/12/13 10:00][30][John Smith][5554215445][#Comment]";
final Pattern pattern = Pattern.compile("\\[#?(.+?)\\]");
final Matcher matcher = pattern.matcher(infoString);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
}
你只需要使.+
非贪婪,它将匹配方括号之间的所有内容。 然后我们使用匹配组来获取我们想要的东西,而不是使用整个匹配的模式,匹配组由(pattern)
表示。 #?
匹配匹配组之前的哈希,以便它不会进入组。
使用matcher.group(1)
检索匹配组。
输出:
03/12/13 10:00
30
John Smith
5554215445
Comment
使用前瞻。 即改变所有你的\\\\[
(在你的正则表达式中)具有正面的lookbehind:
(?<=\\[)
然后用正向前瞻改变你所有的\\\\]
(在你的正则表达式中):
(?=\\])
最后改变\\\\[#
(在你的正则表达式中)有正面的背后:
(?<=\\[#)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.