我正在尝试使用我提供的表达式获取我的匹配器能够找到的字符串。像这样......
if(matcher.find())
System.out.println("Matched string is: " + ?);
适合的代码是什么?根据{{3}}
matcher.group();
方法仅返回与
相同的提供输入matcher.group(0);
提前致谢..
编辑:
示例如下:
private static String fileExtensionPattern = ".*<input type=\"hidden\" name=\".*\" value=\".*\" />.*";
private static Matcher fileXtensionMatcher;
private static String input = text "<html><body><table width="96"><tr><td><img src="file:/test" /><input type="hidden" name="docExt" value=".doc" />Employee Trv Log 2011 Training Trip.doc</td></tr></table></body></html>"
private static void findFileExtension() {
System.out.println("** Searching for file extension **");
System.out.println("Looking for pattern: " + fileExtensionPattern);
fileXtensionMatcher = fileXtensionExp.matcher(input);
if(fileXtensionMatcher.find()) {
//the extension expression is contained in the string
System.out.println("Extension expression found.");
System.out.println(fileXtensionMatcher.group());
}
}
获得的结果是:
text "<html><body><table width="96"><tr><td><img src="file:/test" /><input type="hidden" name="docExt" value=".doc" />Employee Trv Log 2011 Training Trip.doc</td></tr></table></body></html>"
答案 0 :(得分:4)
答案 1 :(得分:3)
添加源代码后,我可以向您保证group()
返回整个输入字符串,因为它与您的正则表达式匹配。如果您只想使用<input>
元素:
private static String fileExtensionPattern = "<input type=\"hidden\" name=\".*\" value=\".*\" />";
或使用:
private static String fileExtensionPattern = ".*(<input type=\"hidden\" name=\".*\" value=\".*\" />).*";
. . .
System.out.println(fileXtensionMatcher.group(1));
答案 2 :(得分:2)
看到您的更新后,您似乎需要匹配组。此外,您需要使匹配不贪婪(.*?
而不是.*
)。试试这个:
private static String fileExtensionPattern =
".*<input type=\"hidden\" name=\".*?\" value=\"(.*?)\" />([^<]*)";
// etc.
private static void findFileExtension() {
// etc.
if(fileXtensionMatcher.find()) {
// etc.
System.out.println(fileXtensionMatcher.group(1));
System.out.println(fileXtensionMatcher.group(2));
}
}