我需要编写一个将模式与一行进行匹配的程序,该模式可以是正则表达式或普通模式
示例:
如果模式是“tiger”,则仅包含“tiger”的行应该匹配
如果模式是“^t”,那么以“t”开头的行应该匹配
我已经这样做了:
Blockquote Pattern and Matcher class
问题是,当我使用 Matcher.find()
时,所有正则表达式都匹配,但如果我给出完整模式,则它不匹配。
如果我使用matches()
,那么只有完整的模式才匹配,而不是正则表达式。
我的代码:
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());
}
}
最佳答案
仅当字符串仅包含 t
时,给定正则表达式 ^t
的
matches
才会匹配。
您还需要包含字符串的其余部分才能匹配。您可以通过附加 .*
来实现,这意味着零个或多个通配符。
"^t.*"
此外,在使用匹配
时,^
(以及等效的$
)是可选的。
希望对您有所帮助,我不太清楚您遇到的问题。欢迎澄清。
关于java - java中正则表达式的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19110799/