返回文章列表

Regex Memo

2017-06-21
1 分鐘
RegexJavaScript

Online Resource

Simple Concept

"I have a book"

  • /a/ => I have a book
  • /have/ => I have a book

需要 \ 前綴的字元:$.|?*+()

範例:"Mr.Wang" => /Mr\./ => Mr.Wang

  • . — 任意字元
  • [] — 代表一個位置的多種可能字元
    • [a-zA-Z] — a 到 z、A 到 Z
    • [^a] — 非 'a'
  • \d — 數字 [0-9]
  • \w — 英數字 [A-Za-z0-9_]
  • \s — 空白 [ \n\r\t]
  • \b — 字界
    • "This is a book" => /\bis\b/ => "This is a book"
  • \D — 非數字 [^\d]
  • \W — 非英數字 [^\w]
  • \S — 非空白 [^\s]

Quantifiers(量詞):

  • * — 零或多次
  • + — 至少一次
  • ? — 零或一次
  • {times}{min,max}
    • "Hello world",/l{2}/ => "Hello world"
    • /l{0,2}/ => "Hello world"

Anchors & Operators:

  • /^/ — 開頭
  • /$/ — 結尾
  • | — OR

Code Example

var re = /(w+)s(w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
console.log(newstr) // Smith, John

Reference

原文發表於 Medium

Command Palette

Search for a command to run...