Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正则表达式匹配$symbol后跟任意单词并保留该单词_Java_Regex - Fatal编程技术网

Java 正则表达式匹配$symbol后跟任意单词并保留该单词

Java 正则表达式匹配$symbol后跟任意单词并保留该单词,java,regex,Java,Regex,我正试图想出一个正则表达式模式,但没有用。下面是一些我需要的例子[]将数组表示为输出 输入 输出 [$World] [$John, $pancakes] [My name , John ] 输入 输出 [$World] [$John, $pancakes] [My name , John ] 我设法想出了这个,它符合模式,但没有保留它找到的单词 String test = "My name $is John $Smith"; String[] testSplit = test.s

我正试图想出一个正则表达式模式,但没有用。下面是一些我需要的例子<代码>[]将数组表示为输出

输入

输出

[$World]
[$John, $pancakes]
[My name ,  John ]
输入

输出

[$World]
[$John, $pancakes]
[My name ,  John ]
我设法想出了这个,它符合模式,但没有保留它找到的单词

String test = "My name $is John $Smith";
String[] testSplit = test.split("(\\$\\S+)");
System.out.println(testSplit);
输出

[$World]
[$John, $pancakes]
[My name ,  John ]

正如你所看到的,它完全吞没了我需要的单词,更具体地说,是符合模式的单词。如何让它返回一个只包含所需单词的数组?(如示例所示)

split
仅使用您的模式来分隔字符串。如果要返回匹配的字符串,请尝试以下操作:

String test = "My name $is John $Smith";
Pattern patt = Pattern.compile("(\\$\\S+)");
Matcher matcher = patt.matcher(test);
while (matcher.find()) {
    System.out.println(matcher.group()); 
}

split
接受一个正则表达式,并专门将该正则表达式周围的字符串拆分,以便它拆分的内容不会保留在输出中。如果希望找到的内容被拆分,则应使用
Matcher
类,例如:

String line = "My name $is John $Smith";
Pattern pattern = Pattern.compile("(\\$\\S+)");
Matcher matcher = pattern.matcher(line);

while (matcher.find()) {
    System.out.println(matcher.group(1));
}

这将在字符串中找到模式的所有匹配项并将其打印出来。这些字符串与
split
用于分割字符串的字符串相同。

您可能想看看
split()
的作用:。也许你想要。尝试将其改为
match()
。我知道存在
split()
match()
split()
专门使用正则表达式来工作,这就是问题所在。问题不在于方法,而在于使其工作所需的正则表达式。您的正则表达式正在工作。你只是用错了:)
while(matcher.find())
我不相信正则表达式中的括号是必要的。我只是使用了匹配的OP正则表达式。也许你在这一点上也是对的。同时给出同样的答案。好的一个:D.
matcher.group()
matcher.group(1)
之间有什么区别?这两个组都尝试了,并且都有相同的输出。在这种情况下是相同的,因为您只有一个匹配组。检查
group(int)
的规格:是的,我相信
matcher.group()
matcher.group(0)
相同,即匹配的整个输入。在这里,不需要使用捕获组,但对我来说,更自然的做法是使用它们,以防您想要匹配与您正在搜索的内容稍有不同的内容。正确
matcher.group()
捕获整个表达式,就像
matcher.group(0)
捕获整个表达式一样。