我正在寻找正确的正则表达式,以提供以下结果:
我目前有:
Pattern pattern = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");..。但下面的例子并不完全奏效。谁能帮我做这件事?
示例:
发布于 2012-10-05 08:51:25
我不确定您是否可以在一个Matcher.match调用中做到这一点,但是可以使用一个循环来完成。
这段代码通过反复使用Matcher.find()解决了上面提到的所有情况:
Pattern pattern = Pattern.compile("\"([^\"]+)\"|'([^']+)'|\\S+");
List<String> testStrings = Arrays.asList("foo bar", "\"foo bar\"","'foo bar'", "'foo bar", "\"'foo bar\"", "foo bar'", "foo bar\"", "\"foo bar\" \"stack overflow\"", "\"foo' bar\" \"stack overflow\" how do you do");
for (String testString : testStrings) {
int count = 1;
Matcher matcher = pattern.matcher(testString);
System.out.format("* %s%n", testString);
while (matcher.find()) {
System.out.format("\t* group%d: %s%n", count++, matcher.group(1) == null ? matcher.group(2) == null ? matcher.group() : matcher.group(2) : matcher.group(1));
}
}这些指纹:
* foo bar
* group1: foo
* group2: bar
* "foo bar"
* group1: foo bar
* 'foo bar'
* group1: foo bar
* 'foo bar
* group1: 'foo
* group2: bar
* "'foo bar"
* group1: 'foo bar
* foo bar'
* group1: foo
* group2: bar'
* foo bar"
* group1: foo
* group2: bar"
* "foo bar" "stack overflow"
* group1: foo bar
* group2: stack overflow
* "foo' bar" "stack overflow" how do you do
* group1: foo' bar
* group2: stack overflow
* group3: how
* group4: do
* group5: you
* group6: do发布于 2012-10-05 08:20:29
只要你有配对(让它是引号或大括号),你就离开正则表达式,进入语法领域,语法领域需要解析器。
我把你交给ultimate answer to this question
更新:
再解释一点。
语法通常表示为:
construct -> [set of constructs or terminals]例如,对于引号
doblequotedstring := " simplequotedstring "
simplequotedstring := string ' string
| string '
| ' string
| '这是一个简单的例子,将有适当的语法例句在互联网上引用。
为此,我使用了aflex和ajacc (对于Ada;在Java中,使用了exist、jflex和jjacc)。将标识符列表传递给aflex,生成一个输出,将该输出和语法传递给ajacc,您将得到一个Ada解析器。由于我使用它们已经有很长时间了,我不知道是否有更精简的解决方案,但在基本情况下,它将需要同样的输入。
https://stackoverflow.com/questions/12742232
复制相似问题