例如,我有以下文本和电子邮件:
String text ="For move information please contact us: [email protected], ask Peter to help."
String email="[email protected]";
因此,我想得到两个10个字符大小的字符串,一个来自电子邮件的左侧,另一个来自右侧。结果我想看:左-联系我们:右:,问皮特
现在,while循环中的matcher.find()返回false。结果,leftContext和rightContext均为null。
这是我的代码:
String email = "[email protected]";
int nLeft = 5;
int nRight = 5;
String leftContext;
String rightContext;
String wordDelRegEx = "[^а-яА-Яa-zA-Z0-9.-]+?";
String leftRegEx = "(\\w{" + nLeft + "})";
String rightRegEx = "(\\w{" + nRight + "})";
//matches something like: aaaaaaa [email protected] bbbbbbbbbb
String contextRe = leftRegEx + wordDelRegEx +email + wordDelRegEx + rightRegEx;
String h ="For move information please contact us: [email protected], ask Peter to help."
Pattern pattern = Pattern.compile(contextRe);
Matcher matcher = pattern.matcher(h);
while (matcher.find()) {
leftContext = matcher.group(1);
rightContext = matcher.group(2);
}
System.out.println("Left: " + leftContext);
System.out.println("Right: " + rightContext);
使用以下命令,因为您的字符串包含冒号(:),逗号(,)和空格(\ s):
没有使用wordDelRegEx变量:
String leftRegEx = "([\\w\\s,:]{" + nLeft + "})";
String rightRegEx = "([\\w\\s,:]{" + nRight + "})";
//匹配类似内容:aaaaaaa [email protected] bbbbbbbbbb
String contextRe =leftRegEx+ email +rightRegEx;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句