![](/img/trans.png)
[英]How to obtain an result from comparing an input word with elements from an String array Java
[英]Java: Obtain matched string from an input
我試圖使用我提供的表達式獲取我的匹配器能夠找到的字符串。 像這樣的東西......
if(matcher.find())
System.out.println("Matched string is: " + ?);
什么是適當的代碼? 根據甲骨文的說法
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>"
添加源代碼后,我可以向您保證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));
看到您的更新后,您似乎需要匹配組。 你還需要讓你的比賽不貪婪( .*?
而不是.*
)。 嘗試這個:
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));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.