问题描述
|
我有一行:
user1 home1
我可以使用ѭ0来匹配user1,但是不能使用ѭ1来匹配home1。
如何搭配?我不能使用拆分。必须使用正则表达式来实现它。
解决方法
这样的事情也应该起作用:
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+
,然后将所有内容放入第二个捕获组中。
输出值
Group1: [user1] Group2: [home1]
,您不能使用ѭ5来匹配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
另外,.*?
可能不是您所需要的,因为它可以轻松匹配空字符串。当您拥有固定的结构时,您将需要贪婪的匹配。
,我认为这应该可以解决ѭ10
无需像建议的那样使用分组。
然后您得到了Java
while (matcher.find())
循环。