我有一个正则表达式,它是
[\\.|\\;|\\?|\\!][\\s]
。它用于拆分字符串。但是如果这些符号在引号内,我不想让它们被拆分。[\\.|\\;|\\?|\\!][\\s]
。它用于拆分字符串。但是如果这些符号在引号内,我不想让它们被拆分。我建议使用 Pattern 和 Matcher 来代替 split。
以下是示例:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String text = "start. \"in quotes!\"; foo? \"more \\\" words\"; bar";
String simpleToken = "[^.;?!\\s\"]+";
String quotedToken =
"(?x) # enable inline comments and ignore white spaces in the regex \n" +
"\" # match a double quote \n" +
"( # open group 1 \n" +
" \\\\. # match a backslash followed by any char (other than line breaks) \n" +
" | # OR \n" +
" [^\\\\\r\n\"] # any character other than a backslash, line breaks or double quote \n" +
") # close group 1 \n" +
"* # repeat group 1 zero or more times \n" +
"\" # match a double quote \n";
String regex = quotedToken + "|" + simpleToken;
Matcher m = Pattern.compile(regex).matcher(text);
while(m.find()) {
System.out.println("> " + m.group());
}
}
}
生成以下内容:
> start
> "in quotes!"
> foo
> "more \" words"
> bar
正如您所看到的,它还可以处理引号内部的转义引号。
(?:[^\"\']|(?:\".*?\")|(?:\'.*?\'))*? # <-- append the query you wanted to search for - don't use something greedy like .* in the rest of your regex.
要适应您的正则表达式,您可以执行以下操作
。(?:[^\"\']|(?:\".*?\")|(?:\'.*?\'))*?[.;?!]\s*