Java中类似Lisp的字符串匹配

时间:2015-01-13 18:51:21

标签: java regex string

我在匹配此格式的字符串方面遇到了一些麻烦:(foo "bar")。准确地说,我想抓住

  1. 左括号,后跟
  2. 零个或多个空白字符,f.b。
  3. 至少一个单词字符,f.b
  4. 空白,零或更多,f.b。
  5. 一个或多个单词char,用双引号括起来,f.b
  6. 可选的空格和右括号。
  7. 接下来我想提取foobar,但这是一个不同的问题。我设法得到的最好的是\( [\s]? [\w]+ [\s]? \" [\w]+ \" [\s]? \),我一直在使用online resource检查我的正则表达式。

    请指出我的正则表达式有什么问题?

2 个答案:

答案 0 :(得分:1)

正则表达式中还有其他空格字符导致模式不匹配。也不需要方括号。问号标记为零或一次出现但不多于。要标记零或更多,您应使用*。以下内容将使用括在括号中的两个匹配组来匹配字符串和两个组foobar

Pattern pattern = Pattern.compile("\\(\\s*(\\w+)\\s*\"(\\w*)\"\\s*\\)");
Matcher matcher = pattern.matcher("(foo \"bar\")");
if(matcher.find()) {
    System.out.println(matcher.group(1));    // foo
    System.out.println(matcher.group(2));    // bar
}

答案 1 :(得分:0)

  • 您不需要将\w \s[] [\s]括起来,\s与{{1}相同(仅当你应该用[ ]将它们括起来的情况是你想要创建单独的字符类,它结合了已经存在的字符类,如[\s\d],它们代表空白或数字的字符)。
  • 默认情况下,空格也包含在正则表达式中,因此"\s "将匹配两个空格,一个用于\s,另一个用于
  • 零或更多”由*表示,?表示零或一次
  • 如果您想将正则表达式编写为字符串,则还需要通过在其前添加另一个\来转义\

请尝试使用代表

的正则表达式"\\(\\s*\\w+\\s*\"[\\w]+\"\\s*\\)"
\\(         - 1. An opening parenthesis
   \\s*     - 2. Zero or more whitespace chars
   \\w+     - 3. At least one word character
   \\s*     - 4. Whitespace again, zero or more
   \"       - 5. opening quotation
   \\w+     - 5. One or more char - I am not sure which symbols you want to add here
                 but you can for instance add them manually with [\\w+\\-*/=<>()]+
   \"       - 5. closing quotation
   \\s*     - 6. Optional whitespace
\\)         - 6. closing parenthesis

现在,如果您想获得匹配文本的某些部分,可以使用character classes(您希望与未转义的括号匹配的环绕声部分),就像正则表达式\\w+ (\\w+)一样,它会找到成对的单词,但第二个单词将被放入组(索引1)。要获取该组的内容,您只需使用group(index)实例中的Matcher

Pattern pattern = Pattern.compile("\\w+ (\\w+)");
Matcher matcher = pattern.matcher("ab cd efg hi jk");

while (matcher.find()) {
    System.out.println("entire match =\t"+matcher.group());
    System.out.println("second word =\t"+matcher.group(1));
    System.out.println("---------------------");
}

输出:

entire match =  ab cd
second word =   cd
---------------------
entire match =  efg hi
second word =   hi
---------------------