Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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 如何使用正则表达式匹配一行中的两个作品_Java_Regex - Fatal编程技术网

Java 如何使用正则表达式匹配一行中的两个作品

Java 如何使用正则表达式匹配一行中的两个作品,java,regex,Java,Regex,我有一句话: 用户1家庭1 我可以使用“(.*?”匹配user1,但无法使用“(.*?$”匹配home1 如何匹配它们?我不能用split。必须使用regex来实现它。您不能使用?来匹配user1。匹配0或1个字符的 您需要:(\S+)\S+(\S+)您不能使用?来匹配user1。匹配0或1个字符的 您需要:(\S+)\S+(\S+)此模式将匹配两个单词: ^(\w+)\s+(\w+)$ 该模式解释如下: ^ Begin of Line (\w+) One or more

我有一句话:

用户1家庭1

我可以使用
“(.*?”
匹配user1,但无法使用
“(.*?$”
匹配home1


如何匹配它们?我不能用split。必须使用regex来实现它。

您不能使用
来匹配user1。匹配0或1个字符的


您需要:
(\S+)\S+(\S+)

您不能使用
来匹配user1。匹配0或1个字符的


您需要:
(\S+)\S+(\S+)

此模式将匹配两个单词:

^(\w+)\s+(\w+)$
该模式解释如下:

^        Begin of Line
(\w+)    One or more word characters (letters and digits), stored in group $1
\s+      Whitespace, one or more chars
(\w+)    One or more word characters (letters and digits), stored in group $2
$        End of Line

另外,
*?
可能不是您需要的,因为它可以很容易地匹配空字符串。当您有固定结构时,您将需要贪婪匹配。

此模式将匹配两个单词:

^(\w+)\s+(\w+)$
该模式解释如下:

^        Begin of Line
(\w+)    One or more word characters (letters and digits), stored in group $1
\s+      Whitespace, one or more chars
(\w+)    One or more word characters (letters and digits), stored in group $2
$        End of Line

另外,
*?
可能不是您需要的,因为它可以很容易地匹配空字符串。当你有一个固定的结构时,你会想要贪婪的匹配。

像这样的东西也应该有用:

String str = "user1 home1";
Pattern pt = Pattern.compile("(.*)\\s+(.*)");
Matcher matcher = pt.matcher(str);
if (matcher.find()) {
    System.out.println("Group1: [" + matcher.group(1) + "] Group2: [" + matcher.group(2) + ']');
}
捕获第一个捕获组中的所有内容,直到找到一个或多个空格
\\s+
,然后将所有内容放入第二个捕获组

输出
类似的方法也应该有效:

String str = "user1 home1";
Pattern pt = Pattern.compile("(.*)\\s+(.*)");
Matcher matcher = pt.matcher(str);
if (matcher.find()) {
    System.out.println("Group1: [" + matcher.group(1) + "] Group2: [" + matcher.group(2) + ']');
}
捕获第一个捕获组中的所有内容,直到找到一个或多个空格
\\s+
,然后将所有内容放入第二个捕获组

输出
我认为这应该可以解决问题。
“\\w+”

不需要像建议的那样使用分组。
你得到了你的Java
while(matcher.find())
循环。

我认为这应该可以解决问题
“\\w+”

不需要像建议的那样使用分组。
你得到了你的Java
while(matcher.find())
循环