[英]Regular expression in java (java String)
从这里 -> 承包商:“嗨,这是“保罗”,你好吗?” 客户:“嗨....” <-
我只想得到 -> 嗨,这是“保罗”,你好吗? <-
我需要一个 Java 中的正则表达式来做到这一点,我尝试了它,但我正在努力处理内部引号 (\\") 使我发疯。
感谢您的任何提示。
Java 支持lookbehinds ,所以香草正则表达式:
"(.*?(?<!\\))"
在 Java 字符串中(参见https://stackoverflow.com/a/37329801/1225328 ):
\"(.*?(?<!\\\\))\"
实际文本将包含在每个匹配项的第一组中。
演示: https : //regex101.com/r/8OXujX/2
例如,在 Java 中:
String regex = "\"(.*?(?<!\\\\))\"";
String input = "contractor:\"Hi, this is \\\"Paul\\\", how are you?\" client:\"Hi ....\"";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) { // or while (matcher.find()) to iterate through all the matches
System.out.println(matcher.group(1));
} else {
System.out.println("No matches");
}
印刷:
Hi, this is \"Paul\", how are you?
var text1 = "contractor:\"Hi, this is \\\"Paul\\\", how are you?\" client:\"Hi ....\" <-";
var regExWithQuotation = "contractor:(.+\".+\".+) client:";
Pattern p = Pattern.compile(regExWithQuotation);
var m = p.matcher(text1);
;
if (m.find()) {
var res = m.group(1);
System.out.println(res);
}
var regExWithoutQuotation = "contractor:\"(.+\".+\".+)?\" client:";
p = Pattern.compile(regExWithoutQuotation);
m = p.matcher(text1);
if (m.find()) {
var res = m.group(1);
System.out.println(res);
}
输出是:
“嗨,我是‘保罗’,你好吗?”
嗨,这是“保罗”,你好吗?
您可以使用正则表达式(?<=contractor:\\").*(?=\\" client:)
正则表达式说明:
(?<=contractor:\\")
为contractor:\\"
指定正向后视contractor:\\"
.*
指定任何字符(?=\\" client:)
为\\" client:
指定正向前瞻\\" client:
简而言之,任何以contractor:\\"
开头并以\\" client:
开头的内容\\" client:
演示:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "contractor:\"Hi, this is \\\"Paul\\\", how are you?\" client:\"Hi ....\"";
String regex = "(?<=contractor:\").*(?=\" client:)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
输出:
Hi, this is \"Paul\", how are you?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.