例如我有这个文本和电子邮件:
String text ="For move information please contact us: contact@gmail.com, ask Peter to help."
String email="contact@gmail.com";
我希望得到两个10个字符大小的字符串,一个来自电子邮件的左侧,另一个来自右侧。 结果我想看:左 -ntact us:正确 :,问Pete
现在, matcher.find()在while循环中返回 false 。因此, leftContext 和 rightContext 都为空。
这是我的代码:
String email = "contact@gmail.com";
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@gmail.com bbbbbbbbbb
String contextRe = leftRegEx + wordDelRegEx +email + wordDelRegEx + rightRegEx;
String h ="For move information please contact us: contact@gmail.com, 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);
答案 0 :(得分:0)
使用以下字符串包含冒号(:),逗号(,)和空格(\ s):
没有使用wordDelRegEx变量:
String leftRegEx = "([\\w\\s,:]{" + nLeft + "})";
String rightRegEx = "([\\w\\s,:]{" + nRight + "})";
//匹配如下内容:aaaaaaa email@gmail.com bbbbbbbbbb
String contextRe =leftRegEx+ email +rightRegEx;