我在匹配此格式的字符串方面遇到了一些麻烦:(foo "bar")
。准确地说,我想抓住
接下来我想提取foo
和bar
,但这是一个不同的问题。我设法得到的最好的是\( [\s]? [\w]+ [\s]? \" [\w]+ \" [\s]? \)
,我一直在使用online resource检查我的正则表达式。
请指出我的正则表达式有什么问题?
答案 0 :(得分:1)
正则表达式中还有其他空格字符导致模式不匹配。也不需要方括号。问号标记为零或一次出现但不多于。要标记零或更多,您应使用*
。以下内容将使用括在括号中的两个匹配组来匹配字符串和两个组foo
和bar
:
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
---------------------