簡體   English   中英

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=&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>"

為什么你認為group()返回輸入?

根據JavaDoc

返回上一個匹配項匹配的輸入子序列。

換句話說:它返回匹配的輸入部分

添加源代碼后,我可以向您保證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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM