directory

  • preface
  • The rules
  • matching
  • replace
  • The last

preface

Regular expressions are pretty universal, and you’ll need them for almost anything you write. Take a look at some of the features of regular expressions in your application:


The rules

Once you know the rules, there are almost no strings that the regular expression can’t match (manual funny). Here’s a recommended website. It’s very detailed, and I’ll show you how to do it in Android.


matching

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("abcd1234ABCD5678");
Copy the code

The strings in the compile method are regular expressions, in this case “\\d+”(note that the extra \ is an escape character). The strings in the matcher method are the strings to match, in this case “abcd1234ABCD5678”. Then there are four ways to match, including find() and matches():

The serial number methods instructions
1 public boolean lookingAt() Attempts to match the pattern with the input sequence starting at the beginning of the region.
2 public boolean find() Attempts to find the next subsequence of the input sequence that matches the pattern.
3 Public Boolean find(int start) Reset this matcher, and then try to find the next subsequence of the input sequence that matches the pattern, starting with the specified index.
4 public boolean matches() Try to match the entire region to the pattern.
while (m.find()) {
    Log.i("sorrower", m.group());
}
Copy the code

The code above prints the result of a subsequence that matches the regular expression. Of course you can use m.group(x) to get the x matching subsequence. Use m.start() and m.end() to obtain the position after the start and end of the subsequence. The return value matches() indicates whether the match was successful.


replace

In addition to matching, regular expression substitution is also fine.

The serial number methods instructions
1 public Matcher appendReplacement(StringBuffer sb, String replacement) Implement non-terminal add and replace steps.
2 public StringBuffer appendTail(StringBuffer sb) Implement terminal add and replace steps.
3 public String replaceAll(String replacement) The replacement pattern matches each subsequence of the input sequence with the given replacement string.
4 public String replaceFirst(String replacement) The first subsequence of the input sequence that matches the given replacement string.
5 public static String quoteReplacement(String s) Returns a literal replacement string for the specified string. This method returns a string and works just like a literal string passed to the appendReplacement method of the Matcher class.

The last

Like remember to like or follow me oh ~