我有粗略的几个字符串:
String s = "Rendering content from websiteNAme using user agent userAgentNameWithSpaces ; for user username ; at time someTime";
我想提取websiteName,userAgentNameWithSpaces,username和someTime的值。 我试过以下代码。
private static final Pattern USER_NAME_PATTERN = Pattern.compile("for user.*;");
final Matcher matcher = USER_NAME_PATTERN.matcher(line);
matcher.find() ? Optional.of(matcher.group(group)) : Optional.empty();
它返回整个字符串"用户名"之后,我必须用空字符串替换for用户字符串以获取用户名。 但是,我想知道是否有正则表达式直接获取用户名?
答案 0 :(得分:1)
我认为你想要使用前瞻和外观:
String s = "Rendering content from websiteNAme using user agent userAgentNameWithSpaces ; for user username ; at time someTime";
Pattern USER_NAME_PATTERN = Pattern.compile("(?<=for user).*?(?=;)");
final Matcher matcher = USER_NAME_PATTERN.matcher(s);
matcher.find();
System.out.println(matcher.group(0).trim());
输出:
用户名
答案 1 :(得分:1)
您可以使用正则表达式组:
Pattern pattern = Pattern.compile("for user (\\w+)");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
括号(
和)
形成一个可以由匹配器使用group
方法获得的组(因为它是第一个括号,它是组1)。
\w
表示“单词字符”(字母,数字和_
),+
表示“一个或多个出现次数”。所以\w+
基本上意味着“一个字”(假设您的用户名只有这些字符)。 PS:请注意我必须转义\
,因此生成的表达式为\\w+
。
此代码的输出为:
用户名
如果要匹配所有值(websiteName,userAgentNameWithSpaces等),您可以执行以下操作:
Pattern pattern = Pattern.compile("Rendering content from (.*) using user agent (.*) ; for user (.*) ; at time (.*)");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));
System.out.println(matcher.group(4));
}
输出将是:
websiteNAme
userAgentNameWithSpaces
username
someTime
请注意,如果userAgentNameWithSpaces
包含空格,\w+
将无效(因为\w
与空格不匹配),因此.*
将适用于此情况。< / p>
但您也可以使用[\w ]+
- 括号[]
表示“我内部的任何字符”,因此[\w ]
表示“单词字符或空格”(请注意w
和]
之间有一个空格。所以代码就是(用空格用户名测试):
String s = "Rendering content from websiteNAme using user agent userAgent Name WithSpaces ; for user username ; at time someTime";
Pattern pattern = Pattern.compile("Rendering content from (.*) using user agent ([\\w ]+) ; for user (.*) ; at time (.*)");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));
System.out.println(matcher.group(4));
}
输出将是:
websiteNAme
userAgent Name WithSpaces
username
someTime
注意:您可以在调用matcher.group(n)
之前测试这些组是否匹配。方法matcher.groupCount()
会返回匹配的群组数量(因为如果您拨打matcher.group(n)
并且群组 n 不可用,则会获得IndexOutOfBoundsException
)