[英]How to extract a string after and before a specific word using Java regular expression
[英]Java regular expression get 2 strings before and after a certain word in string
例如,我有以下文本和电子邮件:
String text ="For move information please contact us: contact@gmail.com, ask Peter to help."
String email="contact@gmail.com";
我想要得到两个10个字符大小的字符串,一个来自电子邮件的左侧,另一个来自右侧。 结果我想看 : 左-联系我们: 右 :,问皮特
现在,while循环中的matcher.find()返回false 。 结果, leftContext和rightContext均为null。
这是我的代码:
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);
使用以下命令,因为您的字符串包含冒号(:),逗号(,)和空格(\\ s):
没有使用wordDelRegEx变量:
String leftRegEx = "([\\w\\s,:]{" + nLeft + "})";
String rightRegEx = "([\\w\\s,:]{" + nRight + "})";
//匹配类似的内容:aaaaaaa email@gmail.com bbbbbbbbbb
String contextRe =leftRegEx+ email +rightRegEx;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.