Reputation: 267
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());
}
}
Upvotes: 1
Views: 1996
Reputation: 48817
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());
Upvotes: 0
Reputation: 55609
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.
Upvotes: 1