简体   繁体   中英

pattern matching with regular expression in java

I need to write a program that matches pattern with a line, that pattern may be a regular expression or normal pattern

Example:
if pattern is "tiger" then line that contains only "tiger" should match
if pattern is "^t" then lines that starts with "t" should match

I have done this with:

Blockquote Pattern and Matcher class

The problem is that when I use Matcher.find() , all regular expressions are matching but if I give full pattern then it is not matching.

If I use matches() , then only complete patterns are matching, not regular expressions.

My code:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class MatchesLooking 
{

    private static final String REGEX = "^f";
    private static final String INPUT =
    "fooooooooooooooooo";
    private static Pattern pattern;
    private static Matcher matcher;

    public static void main(String[] args) 
    {

        // Initialize
        pattern = Pattern.compile(REGEX);
        matcher = pattern.matcher(INPUT);

        System.out.println("Current REGEX is: "
                       + REGEX);
        System.out.println("Current INPUT is: "
                       + INPUT);

        System.out.println("find(): "
        + matcher.find());
        System.out.println("matches(): "
        + matcher.matches());
    }
}

matches given a regex of ^t would only match when the string only consists of a t .

You need to include the rest of the string as well for it to match. You can do so by appending .* , which means zero or more wildcards.

"^t.*"

Also, the ^ (and equivalently $ ) is optional when using matches .

I hope that helps, I'm not entirely clear on what you're struggling with. Feel free to clarify.

This is how Matcher works:

while (matcher.find()) {
    System.out.println(matcher.group());
}

If you're sure there could be only one match in the input, then you could also use:

System.out.println("find(): " + matcher.find());
System.out.println("matches(): " + matcher.group());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM