Regular expressions
Keywords: regular expressions, Pattern,matcher, string methods, Split,replace
The former instrument sets up a flag, which is to be done here, is the regular expression, which is a tool that existed very early in the standard UNIX toolset, such as SED and awk. However, the applications of the UNIX system are still able to see it in the Javascript,java,python,perl, and so on, whenever we see the fingers of others writing a subtle handful of regular work on our several check code, the heart silently raised a feeling of envy , at the same time can only hurry to save the few, the next good tinkering continue to use, then, we can read the regular expression, no longer treat them as a heavenly book.
Java programmers are generally not in depth with regular expressions, because we have string and StringBuilder, and we are proud of the powerful Java string processing in front of regular expressions can only be small garbage.
Regular expressions are a powerful and flexible text processing tool that can solve various string processing related problems: matching, selecting, editing, and validating, Java programmers, throwing away split (), replace (), and substring (), Each time through their combination to change to the need to achieve a time we do not have a poem, simply for the computer and for us is a kind of consumption.
First, warm up
First, we introduce some of the most basic regular expression hot-warm-up.
- Regular expressions use backslashes \ to escape special characters, using two backslashes \ \ in Java
- ?: one or No
- +: one or more
- \d: Digital
- (): Grouped in parentheses, as a whole equals a single character
- |: Represents or, typically used with parentheses
Look at the specific code below,
Test scenarios
The test scenario here is the code that uses the file name filter in the previous IO. First we define a string array as the source data.
String[] data = { "a.txt", "+", "12345", "8", "-2", "-2123", "+010" };
These strings basically contain what we want to practiced hand below. Next, define a simple regular to get the numbers.
String regExp = "\\d";// 一位数的正整数字符【只匹配一个】
Then use this regular method as follows:
for (String s : data) { if (Pattern.matches(regExp, s)) logger.info(s);}
This means traversing a string array, and if it matches the regular expression, print it (just a test scenario, and the pattern and Matcher are described in more detail below). The output of this code is:
09:21:02[testRegExp]: 8
Start testing
The regular expression we write in the above test scenario is "\\d", matching only one positive integer character. Start the formal warm-up test below.
regExp = "\\d+";// 正数数字【加号+代表一个或者多个】
09:33:48[testRegExp]: 1234509:33:48[testRegExp]: 8
regExp = "-?\\d+";// 数字(包括正数和负数)
09:34:27[testRegExp]: 1234509:34:27[testRegExp]: 809:34:27[testRegExp]: -209:34:27[testRegExp]: -2123
regExp = "-\\d+";// 所有负数【只匹配以一个字符‘-’开头的】
09:34:49[testRegExp]: -209:34:49[testRegExp]: -2123
regExp = "-\\d";// 只有一位数的负数【只匹配以一个字符‘-’开头的,同时只有一位整数的字符串】
09:35:06[testRegExp]: -2
From the above four paragraphs can be summed up, assuming that there is a character a, we match its various cases of the regular expression in the way:
A (one or none), a (only one), A + (one or more)
regExp = "\\+";// 内容为加号的字符串
regExp = "\\+\\d+";// 以加号开头接整数的字符串
09:37:59[testRegExp]: +010
These two paragraphs mean that we want to match the plus sign, but the plus sign itself is part of the regular expression, so add \ \ to escape it as a normal character.
regExp = "(\\+|-)\\d+";// 以一个加号或者一个负号开头的数字
09:39:29[testRegExp]: -209:39:29[testRegExp]: -212309:39:29[testRegExp]: +010
regExp = "(\\+|-)?\\d+";// 以一个加号或者一个负号开头或者没有符号的数字
09:39:47[testRegExp]: 1234509:39:47[testRegExp]: 809:39:47[testRegExp]: -209:39:47[testRegExp]: -212309:39:47[testRegExp]: +010
In these two paragraphs we use parentheses to denote a grouping, and the entire parenthesis is equivalent to a single character.
Regular expressions in the string method
The above mentioned in the Java string split,replace, and so on, they are supporting regular expression, so do not just use their string simple operation, partition the replacement part, you can apply the regular expression, the regular expression gives us the function of the last fuzzy query programming, Using the string itself as a search parameter, a regular expression can represent a richer content.
String regex = " ";// 按空格来划分字符串regex = "\\W+";// 正则选择出非单词字符,split过滤一遍以后剩下纯单词,删除其他符号regex = "g\\W+";// 字母n后面跟着非单词字符,也就是‘n后面有空格字符’,split以后就去掉了n和这个空格String preface = "I wish I had this book when I started programming... I recommend this book to every student as well as beginner and intermediate Java programmer.";String[] a = preface.split(regex);logger.info(a.length + " " + Arrays.toString(a));
11:03:17[testSplit]: 2 [I wish I had this book when I started programmin, I recommend this book to every student as well as beginner and intermediate Java programmer.]
logger.info(preface.replaceFirst("p\\w+", "heyhey"));// 将第一个p打头的单词改为heyheylogger.info(preface.replaceAll("p\\w+", "heyhey"));// 将全部p打头的单词改为heyhey
11:03:17[testSplit]: I wish I had this book when I started heyhey... I recommend this book to every student as well as beginner and intermediate Java programmer.11:03:17[testSplit]: I wish I had this book when I started heyhey... I recommend this book to every student as well as beginner and intermediate Java heyhey.
For specific explanations, please see the comments in the code directly.
Second, Java.util.regex
The preceding regular expression is a string object, but Java supports specialized, more powerful regular expression-related classes. Here's how to create a regular expression in Java, mainly the pattern class and the Matcher class in Java.util.regex.
Pattern p = Pattern.compile("a*b");Matcher m = p.matcher("aaaaab");boolean b = m.matches();logger.info(b);
输出:true
If you do not involve pattern reuse, match reuse, you can change to
logger.info(Pattern.matches("a*b", "aaaab"));
11:22:59[testRegex]: true
Described above?, unsigned and +, each representing one or none, one, one or more, then is there a symbol that can overwrite all of them, representing no or there, one or more?
- *: Contains one or more of the characters, or does not contain the character
and the general regular expression is the lowercase letter represents the meaning of itself, and its capitalization represents the opposite meaning, as mentioned above,
- \w: Word characters, uppercase and lowercase letters plus numbers
- \w: non-word characters
- ^: Non-
So \w can also be expressed as [^\w], the same,
- \d: Matching number [0-9]
- \d: Non-digital [^0-9]
- []: square brackets, which represent any of these characters, equal to the grouping of parentheses plus |
- \s: Whitespace (Space, tab, line feed, page feed, or carriage return)
- \s: Non-whitespace character [^\s]
And then, again, several square brackets inside the case,
- [ABC]: a single character containing any of the ABC characters (note that there is only one character)
Pattern p = Pattern.compile("[abc]");logger.info(p.matcher("abc").matches());logger.info(p.matcher("b").matches());logger.info(p.matcher("ab").matches());logger.info(p.matcher("c").matches());
14:15:57[testRegex]: false14:15:57[testRegex]: true14:15:57[testRegex]: false14:15:57[testRegex]: true
The effect of [ABC] and (A|b|c) is the same.
- [A-za-z]: Also a single character with a character range of uppercase and lowercase letters.
Square brackets if not added, * or +, the effect is the same as an unsigned single character, representing only one character.
- [Abc[hij]]: Also matches a single character, the range is Abchij, and set.
- [A-Z&&[HCJ]]: Take the intersection, HCJ in a A-Z range, so the final meaning is to match a character, the character range in HCJ any one.
Number of settings
Regular expressions can contract the number of occurrences of a character, the above, *,+ have been mentioned, then the specific quantifier how to set it?
Pattern p = Pattern.compile("[a-z]{3}");logger.info(p.matcher("abc234").matches());logger.info(p.matcher("ccc").matches());logger.info(p.matcher("ab").matches());logger.info(p.matcher("c").matches());
15:12:49[testRegex]: false15:12:49[testRegex]: true15:12:49[testRegex]: false15:12:49[testRegex]: false
Summarize
This article describes the regular expression content to get started, but for Java programmers to deal with common problems is enough, especially to read the existing code, tinkering with the ability to have some.
Regular Expressions--java programmers know you