JAVA基礎 - 正則表達式

正則表達式, 符號對照及範例

正則表達式: 定義一個搜索模式的字符串。

正則表達式可以用於搜索、编輯和操作文本.
用有限的符號,表達無限的序列

this is text
精確匹配字符串 “this is text”

this\s + is\s + text
匹配單詞”this” 後跟一個或多個字符
後跟詞 “is” 後跟一個或多個字符
後跟詞 “text”

^\d+(\.\d+)?
^ 定義模式必須匹配字符串的開始
d+ 匹配一個或多個數字
? 表明小括號内的語句可有可無
\. 匹配 “.”
()小括号表示分组
例如:”5”、”1.5” “2.21”

正規表達式規則

常用匹配符號

. 匹配所有單個字符,除了換行字符

^regex 匹配字符串开头

regex$ 匹配字符串结尾

[abc] 複選定義,匹配字母 a 或 b 或 c

[abc][vz] 複選定義,匹配字母 a 或 b 或 c,後面接著 v 或 z

[^abc] 當插入符 ^ 在中括號中以第一個字符開始顯示,則表示否定模式。此模式匹配所有字符,除了 a 或 b 或 c

[a-d1-7] 範圍匹配,字母 a 到 d 和數字从從1 到 7 之間,但不匹配 d1

XZ 匹配 X 後直接接著 Z

X|Z 匹配 X 或 Z

元字符

元字符是一個預先定義的字符。

\d 匹配一個數字,是 [0-9] 的簡寫

\D 匹配一個非數字,是 [^0-9] 的簡寫

\s 匹配一個空格,是 [ \t\n\x0b\r\f] 的簡寫

\S 匹配一個非空格

\w 匹配一個單字字符(大小寫字母、數字、下划線),是 [a-zA-Z_0-9] 的簡寫

\W 匹配一個非單字字符(除了大小寫字母、數字、下划線之外的字符),等同于 [^\w]

限定字符

限定符定限了一個元素可以發生的頻率。

*
匹配 >=0 個,是 {0,} 的簡寫
X 表示匹配零個或多個字母 X
.
表示匹配任何字符串

+
匹配 >=1 個,是 {1,} 的簡寫
X+ 表示匹配一個或多個字母 X

?
匹配 1 個或 0 個,是 {0,1} 的簡寫
X? 表示匹配 0 個或 1 個字母 X

{X}
只匹配 X 個字符
\d{3} 表示匹配 3 個數字
.{10} 表示匹配任何長度是 10 的字符串

{X,Y}
匹配 >=X 且 <=Y 個
\d{1,4} 表示匹配至少 1 個最多 4 個數字

*?
如果 ? 是限定符 * 或 + 或 ? 或 {} 後面的第一個字符,
那麽表示非貪婪模式(盡可能少的匹配字符),而不是默認的貪婪模式

Leetcode 實例

125. Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1: Input: "A man, a plan, a canal: Panama" Output: true

Example 2: Input: "race a car" Output: false

  • MySolution:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public class Solution {
    public boolean isPalindrome(String s) {
    String str = new String ();
    str = s.toLowerCase().replaceAll("[^(a-zA-Z0-9)]", "").replaceAll("\\pP","");
    //"\\pP"用來去除所有符號,不包括空格

    StringBuffer strb = new StringBuffer(str);
    //需用StringBuffer的reverse方法

    String strv = new String(strb.reverse());
    //需用String的CompareTo方法

    if(str.compareTo(strv)!= 0){
    return false;
    }
    else{
    return true;
    }
    }
    }
  • BetterSolution:

    1
    2
    3
    4
    5
    6
    7
    public class Solution {
    public boolean isPalindrome(String s) {
    String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
    String rev = new StringBuffer(actual).reverse().toString();
    return actual.equals(rev);
    }
    }

引用:https://juejin.im/post/5acb0c526fb9a028ba1fc602