java正则表达式检查字符串是否匹配,java正则表达式,package cn.o
分享于 点击 34921 次 点评:77
java正则表达式检查字符串是否匹配,java正则表达式,package cn.o
package cn.outofmemory.snippets.core;import java.util.regex.Matcher;import java.util.regex.Pattern;public class CheckIfAStringMatchesAPattern { public static void main(String[] args) { String patternStr = "test"; Pattern pattern = Pattern.compile(patternStr); String input = "this fails"; // create a matcher that will match the given input against this pattern Matcher matcher = pattern.matcher(input); boolean matchFound = matcher.matches(); System.out.println(input + " - matches: " + matchFound); input = "this passes the test"; // reset the matcher with a new input sequence matcher.reset(input); matchFound = matcher.matches(); System.out.println(input + " - matches: " + matchFound); // Attempts to match the input sequence, starting at the beginning // of the region, against the pattern matchFound = matcher.lookingAt(); System.out.println(input + " - matches from the beginning: " + matchFound); }}
输出:
this fails - matches: falsethis passes the test - matches: falsethis passes the test - matches from the beginning: false
用户点评