[Java] regular expressions based on java

Java basic regular expression

Regular expression example

Regular expression description
this is text Matches the string "this is text"
this\s+is\s+text Note the \s+ in the string . The \s+ after the matching word "this" can match multiple spaces, followed by the is string, and then \s+ matches multiple spaces and then followed by the text string. Can match this instance: this is text
^\d+(.\d+)? ^ Defines what starts with \d+ to match one or more digits? The options in brackets are optional. Examples of matching ".": "5", "1.5" and "2.21".

The java.util.regex package mainly includes the following three categories:

  • Pattern class:

    The pattern object is a compiled representation of a regular expression. The Pattern class has no public constructor. To create a Pattern object, you must first call its public static compilation method, which returns a Pattern object. This method accepts a regular expression as its first parameter.

  • Matcher class:

    The Matcher object is an engine for interpreting and matching input strings. Like the Pattern class, Matcher has no public constructor. You need to call the matcher method of the Pattern object to obtain a Matcher object.

  • PatternSyntaxException:

    PatternSyntaxException is a non-mandatory exception class, which represents a syntax error in a regular expression pattern.

Regular expressions are used in the following examples . *runoob.* is used to find out whether the string contains runoob substrings:

import java.util.regex.*;
 
class RegexExample1{
    
    
   public static void main(String args[]){
    
    
      String content = "I am noob " +
        "from runoob.com.";
 
      String pattern = ".*runoob.*";
 
      boolean isMatch = Pattern.matches(pattern, content);
      System.out.println("字符串中是否包含了 'runoob' 子字符串? " + isMatch);
   }
}

The example output is:

​ Does the string contain the'runoob' substring? true

Capture group

A capture group is a method that treats multiple characters as a single unit. It is created by grouping characters in parentheses.

For example, the regular expression (dog) creates a single group, which contains "d", "o", and "g".

Capture groups are numbered by counting their opening brackets from left to right. For example, in the expression ((A)(B(C))), there are four such groups:

  • ((A)(B©))
  • (A)
  • (B©)
  • ©

You can check how many groups the expression has by calling the groupCount method of the matcher object. The groupCount method returns an int value, indicating that the matcher object currently has multiple capture groups.

There is also a special group (group(0)), which always represents the entire expression. This group is not included in the return value of groupCount.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexMatches
{
    
    
    public static void main( String args[] ){
    
    
 
      // 按指定模式在字符串查找
      String line = "This order was placed for QT3000! OK?";
      String pattern = "(\\D*)(\\d+)(.*)";
 
      // 创建 Pattern 对象
      Pattern r = Pattern.compile(pattern);
 
      // 现在创建 matcher 对象
      Matcher m = r.matcher(line);
      if (m.find( )) {
    
    
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
         System.out.println("Found value: " + m.group(3) ); 
      } else {
    
    
         System.out.println("NO MATCH");
      }
   }
}

Regular expression syntax

character Description
\ Mark the next character as a special character, text, backreference, or octal escape character. For example, "n" matches the character "n". "\n" matches a newline character. The sequence "\\"match"\","\("match"(".
^ Matches the position at the beginning of the input string. If the Multiline property of the RegExp object is set , ^ will also match the position after "\n" or "\r".
$ Matches the position at the end of the input string. If the Multiline property of the RegExp object is set , $ will also match the position before "\n" or "\r".
* Match the preceding character or sub-expression zero or more times. For example, zo* matches "z" and "zoo". * Equivalent to {0,}.
+ Match the preceding character or subexpression one or more times. For example, "zo+" matches "zo" and "zoo" but not "z". + Is equivalent to {1,}.
? Match the preceding character or subexpression zero or one time. For example, "do(es)?" matches "do" or "do" in "does". ? Equivalent to {0,1}.
{ n} n is a non-negative integer. Match exactly n times. For example, "o{2}" does not match the "o" in "Bob", but it matches the two "o"s in "food".
{ n,} n is a non-negative integer. Match at least n times. For example, "o{2,}" does not match the "o" in "Bob", but matches all o in "foooood". "o{1,}" is equivalent to "o+". "o{0,}" is equivalent to "o*".
{ n,m} m and n are non-negative integers, where n <= m . Match at least n times and at most m times. For example, "o{1,3}" matches the first three o's in "fooooood". 'o{0,1}' is equivalent to'o?'. Note: You cannot insert spaces between commas and numbers.
? When this character immediately follows any other qualifiers (*, +,?, { n }, { n ,}, { n , m }), the matching pattern is "non-greedy". The "non-greedy" pattern matches the searched string as short as possible, while the default "greedy" pattern matches the searched string as long as possible. For example, in the string "oooo", "o+?" matches only a single "o", and "o+" matches all "o"s.
. Match any single character except "\r\n". To match any character including "\r\n", use a pattern such as "[\s\S]".
(pattern) Match pattern and capture the matched sub-expression. You can use the $0...$9 attributes to retrieve captured matches from the result "match" set. To match bracket characters (), use "(" or ")".
(?:pattern) Matches the pattern but does not capture the matched sub-expression, that is, it is a non-capturing match and does not store the match for later use. This is useful when combining pattern parts with the "or" character (|). For example,'industr(?:y|ies) is a more economical expression than'industry|industries'.
(?=pattern) Perform forward prediction lookahead search sub-expression that matches the string at the beginning of the string matching pattern . It is a non-capturing match, that is, a match that cannot be captured for later use. For example,'Windows (?=95|98|NT|2000)' matches "Windows" in "Windows 2000" but not "Windows" in "Windows 3.1". Prediction first does not occupy characters, that is, after a match occurs, the search for the next match immediately follows the previous match, not after the characters that make up the prediction first.
(?!pattern) A sub-expression that performs a backward prediction look-ahead search that matches a search string that is not at the beginning of the string that matches the pattern . It is a non-capturing match, that is, a match that cannot be captured for later use. For example,'Windows (?!95|98|NT|2000)' matches "Windows" in "Windows 3.1" but not "Windows" in "Windows 2000". Prediction first does not occupy characters, that is, after a match occurs, the search for the next match immediately follows the previous match, not after the characters that make up the prediction first.
x | and Match x or y . For example,'z|food' matches "z" or "food". '(z|f)ood' matches "zood" or "food".
[xyz] character set. Match any character contained. For example, "[abc]" matches the "a" in "plain".
[^xyz] Reverse character set. Matches any characters that are not included. For example, "[^abc]" matches "p", "l", "i", "n" in "plain".
[a-z] Character range. Match any character in the specified range. For example, "[az]" matches any lowercase letter in the range "a" to "z".
[^a-z] 反向范围字符。匹配不在指定的范围内的任何字符。例如,"[^a-z]"匹配任何不在"a"到"z"范围内的任何字符。
\b 匹配一个字边界,即字与空格间的位置。例如,“er\b"匹配"never"中的"er”,但不匹配"verb"中的"er"。
\B 非字边界匹配。“er\B"匹配"verb"中的"er”,但不匹配"never"中的"er"。
\cx 匹配 x 指示的控制字符。例如,\cM 匹配 Control-M 或回车符。x 的值必须在 A-Z 或 a-z 之间。如果不是这样,则假定 c 就是"c"字符本身。
\d 数字字符匹配。等效于 [0-9]。
\D 非数字字符匹配。等效于 [^0-9]。
\f 换页符匹配。等效于 \x0c 和 \cL。
\n 换行符匹配。等效于 \x0a 和 \cJ。
\r 匹配一个回车符。等效于 \x0d 和 \cM。
\s 匹配任何空白字符,包括空格、制表符、换页符等。与 [ \f\n\r\t\v] 等效。
\S 匹配任何非空白字符。与 [^ \f\n\r\t\v] 等效。
\t 制表符匹配。与 \x09 和 \cI 等效。
\v 垂直制表符匹配。与 \x0b 和 \cK 等效。
\w 匹配任何字类字符,包括下划线。与"[A-Za-z0-9_]"等效。
\W 与任何非单词字符匹配。与"[^A-Za-z0-9_]"等效。
\xn 匹配 n,此处的 n 是一个十六进制转义码。十六进制转义码必须正好是两位数长。例如,"\x41"匹配"A"。"\x041"与"\x04"&"1"等效。允许在正则表达式中使用 ASCII 代码。
*num* 匹配 num,此处的 num 是一个正整数。到捕获匹配的反向引用。例如,"(.)\1"匹配两个连续的相同字符。
*n* 标识一个八进制转义码或反向引用。如果 *n* 前面至少有 n 个捕获子表达式,那么 n 是反向引用。否则,如果 n 是八进制数 (0-7),那么 n 是八进制转义码。
*nm* 标识一个八进制转义码或反向引用。如果 *nm* 前面至少有 nm 个捕获子表达式,那么 nm 是反向引用。如果 *nm* 前面至少有 n 个捕获,则 n 是反向引用,后面跟有字符 m。如果两种前面的情况都不存在,则 *nm* 匹配八进制值 nm,其中 nm 是八进制数字 (0-7)。
\nml n 是八进制数 (0-3),ml 是八进制数 (0-7) 时,匹配八进制转义码 nml
\un 匹配 n,其中 n 是以四位十六进制数表示的 Unicode 字符。例如,\u00A9 匹配版权符号 (©)。

根据 Java Language Specification 的要求,Java 源代码的字符串中的反斜线被解释为 Unicode 转义或其他字符转义。因此必须在字符串字面值中使用两个反斜线,表示正则表达式受到保护,不被 Java 字节码编译器解释。例如,当解释为正则表达式时,字符串字面值 “\b” 与单个退格字符匹配,而 “\b” 与单词边界匹配。字符串字面值 “(hello)” 是非法的,将导致编译时错误;要与字符串 (hello) 匹配,必须使用字符串字面值 “\(hello\)”。

Matcher 类的方法

  • 索引方法

索引方法提供了有用的索引值,精确表明输入字符串中在哪能找到匹配:

序号 方法及说明
1 public int start() 返回以前匹配的初始索引。
2 public int start(int group) 返回在以前的匹配操作期间,由给定组所捕获的子序列的初始索引
3 public int end() 返回最后匹配字符之后的偏移量。
4 public int end(int group) 返回在以前的匹配操作期间,由给定组所捕获子序列的最后字符之后的偏移量。
  • 研究方法

研究方法用来检查输入字符串并返回一个布尔值,表示是否找到该模式:

序号 方法及说明
1 public boolean lookingAt() 尝试将从区域开头开始的输入序列与该模式匹配。
2 public boolean find() 尝试查找与该模式匹配的输入序列的下一个子序列。
3 public boolean find(int start**)** 重置此匹配器,然后尝试查找匹配该模式、从指定索引开始的输入序列的下一个子序列。
4 public boolean matches() 尝试将整个区域与模式匹配。
  • 替换方法

替换方法是替换输入字符串里文本的方法:

序号 方法及说明
1 public Matcher appendReplacement(StringBuffer sb, String replacement) 实现非终端添加和替换步骤。
2 public StringBuffer appendTail(StringBuffer sb) 实现终端添加和替换步骤。
3 public String replaceAll(String replacement) 替换模式与给定替换字符串相匹配的输入序列的每个子序列。
4 public String replaceFirst(String replacement) 替换模式与给定替换字符串匹配的输入序列的第一个子序列。
5 public static String quoteReplacement(String s) 返回指定字符串的字面替换字符串。这个方法返回一个字符串,就像传递给Matcher类的appendReplacement 方法一个字面字符串一样工作。
  • start 和 end 方法

下面是一个对单词 “cat” 出现在输入字符串中出现次数进行计数的例子:

RegexMatches.java 文件代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexMatches
{
    
    
    private static final String REGEX = "\\bcat\\b";
    private static final String INPUT =
                                    "cat cat cat cattie cat";
 
    public static void main( String args[] ){
    
    
       Pattern p = Pattern.compile(REGEX);
       Matcher m = p.matcher(INPUT); // 获取 matcher 对象
       int count = 0;
 
       while(m.find()) {
    
    
         count++;
         System.out.println("Match number "+count);
         System.out.println("start(): "+m.start());
         System.out.println("end(): "+m.end());
      }
   }
}

以上实例编译运行结果如下:

Match number 1
start(): 0
end(): 3
Match number 2
start(): 4
end(): 7
Match number 3
start(): 8
end(): 11
Match number 4
start(): 19
end(): 22

可以看到这个例子是使用单词边界,以确保字母 “c” “a” “t” 并非仅是一个较长的词的子串。它也提供了一些关于输入字符串中匹配发生位置的有用信息。

Start 方法返回在以前的匹配操作期间,由给定组所捕获的子序列的初始索引,end 方法最后一个匹配字符的索引加 1。

  • matches 和 lookingAt 方法

matches 和 lookingAt 方法都用来尝试匹配一个输入序列模式。它们的不同是 matches 要求整个序列都匹配,而lookingAt 不要求。

lookingAt 方法虽然不需要整句都匹配,但是需要从第一个字符开始匹配。

这两个方法经常在输入字符串的开始使用。

我们通过下面这个例子,来解释这个功能:

RegexMatches.java 文件代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexMatches
{
    
    
    private static final String REGEX = "foo";
    private static final String INPUT = "fooooooooooooooooo";
    private static final String INPUT2 = "ooooofoooooooooooo";
    private static Pattern pattern;
    private static Matcher matcher;
    private static Matcher matcher2;
 
    public static void main( String args[] ){
    
    
       pattern = Pattern.compile(REGEX);
       matcher = pattern.matcher(INPUT);
       matcher2 = pattern.matcher(INPUT2);
 
       System.out.println("Current REGEX is: "+REGEX);
       System.out.println("Current INPUT is: "+INPUT);
       System.out.println("Current INPUT2 is: "+INPUT2);
 
 
       System.out.println("lookingAt(): "+matcher.lookingAt());
       System.out.println("matches(): "+matcher.matches());
       System.out.println("lookingAt(): "+matcher2.lookingAt());
   }
}

以上实例编译运行结果如下:

Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
Current INPUT2 is: ooooofoooooooooooo
lookingAt(): true
matches(): false
lookingAt(): false
  • replaceFirst 和 replaceAll 方法

replaceFirst 和 replaceAll 方法用来替换匹配正则表达式的文本。不同的是,replaceFirst 替换首次匹配,replaceAll 替换所有匹配。

下面的例子来解释这个功能:

RegexMatches.java 文件代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexMatches
{
    
    
    private static String REGEX = "dog";
    private static String INPUT = "The dog says meow. " +
                                    "All dogs say meow.";
    private static String REPLACE = "cat";
 
    public static void main(String[] args) {
    
    
       Pattern p = Pattern.compile(REGEX);
       // get a matcher object
       Matcher m = p.matcher(INPUT); 
       INPUT = m.replaceAll(REPLACE);
       System.out.println(INPUT);
   }
}

以上实例编译运行结果如下:

The cat says meow. All cats say meow.
  • appendReplacement 和 appendTail 方法

Matcher 类也提供了appendReplacement 和 appendTail 方法用于文本替换:

看下面的例子来解释这个功能:

RegexMatches.java 文件代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexMatches
{
    
    
   private static String REGEX = "a*b";
   private static String INPUT = "aabfooaabfooabfoobkkk";
   private static String REPLACE = "-";
   public static void main(String[] args) {
    
    
      Pattern p = Pattern.compile(REGEX);
      // 获取 matcher 对象
      Matcher m = p.matcher(INPUT);
      StringBuffer sb = new StringBuffer();
      while(m.find()){
    
    
         m.appendReplacement(sb,REPLACE);
      }
      m.appendTail(sb);
      System.out.println(sb.toString());
   }
}

以上实例编译运行结果如下:

-foo-foo-foo-kkk
  • PatternSyntaxException 类的方法

PatternSyntaxException 是一个非强制异常类,它指示一个正则表达式模式中的语法错误。

The PatternSyntaxException class provides the following methods to help us see what errors have occurred.

Serial number Method and description
1 public String getDescription() Get the description of the error.
2 public int getIndex() Get the wrong index.
3 public String getPattern() Get the wrong regular expression pattern.
4 public String getMessage() returns a multi-line string containing a description of the syntax error and its index, the wrong regular expression pattern, and a visual indication of the error index in the pattern.

*Disclaimer: This blog post draws on the rookie tutorial! *

Guess you like

Origin blog.csdn.net/qq_42380734/article/details/105369494