Pattern
. 一个引擎通过解释Pattern执行匹配操作字符序列。A matcher is created from a pattern by invoking the pattern's matcher
method. Once created, a matcher can be used to perform three different kinds of match operations:
Pattern
describes a string pattern.Matcher
tests a string to see if it matches the pattern. PatternSyntaxException
tells you that something wasn't acceptable about the pattern that you tried to define.
二、Regex pattern syntax
. Any character?Zero (0) or one (1) of what came before
* Zero (0) or more of what came before+One (1) or more of what came before
[] A range of characters or digits^Negation of whatever follows (that is, "not whatever")
d Any digit (alternatively, [0-9])DAny nondigit (alternatively, [^0-9])
s Any whitespace character (alternatively, [
f
])
S Any nonwhitespace character (alternatively, [^
f
])
w Any word character (alternatively, [a-zA-Z_0-9])
W Any nonword character (alternatively, [^w])
三、test
@Test public void test() {
//Thematches()
method in theMatcher
class matches the regular expression against the whole text
//The methodsstart()
andend()
will give the indexes into the text where the found match starts and ends.
//Find a string of the form A or a followed by zero or more characters, followed by string.
Pattern pattern = Pattern.compile("[Aa].*string"); Matcher matcher = pattern.matcher("A string"); boolean didMatch = matcher.matches(); System.out.println(didMatch); int patternStartIndex = matcher.start(); System.out.println(patternStartIndex); int patternEndIndex = matcher.end(); System.out.println(patternEndIndex); }
---------
true
0
8
@Test public void test1() { //lookingAt() //If your string had more elements than the number of characters in the pattern you searched for, // you could use lookingAt() instead of matches(). // The lookingAt() method searches for substring matches for a specified pattern. Pattern pattern = Pattern.compile("[Aa].*string"); Matcher matcher = pattern.matcher("A string with more than just the pattern."); boolean didMatch = matcher.lookingAt(); System.out.println(didMatch); }
---------
true
@Test public void test2() { //find()
//if multiple matches can be found in the text, thefind()
method will find the first, and then for each subsequent call tofind()
it will move to the next match.
String input = "Here is a WikiWord followed by AnotherWikiWord, then SomeWikiWord."; Pattern pattern = Pattern.compile("[A-Z][a-z]*([A-Z][a-z]*)+"); Matcher matcher = pattern.matcher(input); while (matcher.find()) { Logger.getAnonymousLogger().info("Found this wiki word: " + matcher.group()); } }
--------
Found this wiki word: WikiWord
Found this wiki word: AnotherWikiWord
Found this wiki word: SomeWikiWord
参考文章:
http://tutorials.jenkov.com/java-regex/index.html
https://www.ibm.com/developerworks/library/j-perry-regular-expressions/index.html