我正在寻找正确的正则表达式,以便为我提供以下结果:
我目前有:
Pattern pattern = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
...但以下示例并未完全奏效。 谁可以帮我这个?
示例:
答案 0 :(得分:7)
我不确定你是否可以在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
答案 1 :(得分:1)
任何时候你有配对(让它成为引号或大括号)你离开正则表达式领域并进入需要解析器的语法领域。
我会留下ultimate answer to this question
更新:
再解释一下。
语法通常表示为:
construct -> [set of constructs or terminals]
例如,对于引号
doblequotedstring := " simplequotedstring "
simplequotedstring := string ' string
| string '
| ' string
| '
这是一个简单的例子;将有适当的语法示例用于在互联网上引用。
我已经使用了aflex和ajacc(对于Ada;在Java中存在jflex和jjacc)。您将标识符列表传递给aflex,生成输出,将该输出和语法传递给ajacc,然后获得Ada解析器。由于我使用它们已经很多时间了,我不知道是否有更简化的解决方案,但在基本方面它需要相同的输入。