Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Obtain matched string from an input

Tags:

java

regex

I am trying to obtain the string that my matcher is able to find using my provided expression. Something like this..

if(matcher.find())
    System.out.println("Matched string is: " + ?);

What would be the appropriate code for this? According to Oracle the

matcher.group();

method returns only the provided input same as

matcher.group(0);

Thanks in advance..

Edit:

Example follows below:

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());
    }
}

The obtained result is:

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>"
like image 821
arin Avatar asked Nov 05 '25 16:11

arin


1 Answers

Why do you think that group() returns the input?

According to the JavaDoc:

Returns the input subsequence matched by the previous match.

In other words: it returns that part of the input that was matched.

like image 169
Joachim Sauer Avatar answered Nov 07 '25 11:11

Joachim Sauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!