3

我正在尝试使用我提供的表达式获取我的匹配器能够找到的字符串。像这样的东西。。

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=&quot;file:/test&quot;  /><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=&quot;file:/test&quot;  /><input type="hidden" name="docExt" value=".doc" />Employee Trv Log 2011 Training Trip.doc</td></tr></table></body></html>"
4

3 回答 3

4

你为什么认为这会group()返回输入?

根据JavaDoc

返回与前一个匹配项匹配的输入子序列。

换句话说:它返回匹配的那部分输入。

于 2011-09-12T15:37:44.737 回答
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));
于 2011-09-12T15:52:21.897 回答
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));
    }
}
于 2011-09-12T15:52:20.993 回答