2
我有一个正则表达式,它是[\\.|\\;|\\?|\\!][\\s]
这是用来分割一个字符串。但是如果它在引号中,我不希望它分裂. ; ? !
。RegEx忽略引号之间的文本
我有一个正则表达式,它是[\\.|\\;|\\?|\\!][\\s]
这是用来分割一个字符串。但是如果它在引号中,我不希望它分裂. ; ? !
。RegEx忽略引号之间的文本
我不想使用拆分,而是使用模式&匹配器。
一个演示:
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*
我想你需要开始思考*解析*,不是正则表达式分裂。尽管如此,这将更容易回答一些示例输入。 – deceze 2011-02-07 03:56:10