跳到主要内容

正则常用场景

· 阅读需 3 分钟

正则表达式是用于匹配字符串中字符组合的模式。要么匹配字符,要么匹配位置。这里介绍几种经常使用正则的场景。

RegExp.test

用来查看正则表达式与指定的字符串是否匹配。返回 true 或 false。

(str: string): boolean
var regex = /foo/g

// regex.lastIndex is at 0
regex.test('foo') // true

// regex.lastIndex is now at 3
regex.test('foo') // false

RegExp.exec

在一个指定字符串中执行一个搜索匹配。返回一个结果数组或 null。

(str: string): null | [匹配的全部字符串, ...括号中的分组捕获]
const regex1 = RegExp('foo*', 'g')
const str1 = 'table football, foosball'
let array1

while ((array1 = regex1.exec(str1)) !== null) {
console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`)
// expected output: "Found foo. Next starts at 9."
// expected output: "Found foo. Next starts at 19."
}

String.search

执行正则表达式和 String 对象之间的一个搜索匹配。

(reg: regexp): number
const paragraph = 'abcd'

console.log(paragraph.search(/e/)) // -1
console.log(paragraph.search(/a/)) // 0

String.match

检索返回一个字符串匹配正则表达式的结果

(reg: regexp): [...与完整正则表达式匹配的所有结果] | null | [匹配的全部字符串, ...括号中的分组捕获]
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.'
const regex = /[A-Z]/g
const found = paragraph.match(regex)

console.log(found)
// expected output: Array ["T", "I"]

String.replace

方法返回一个由替换值(replacement)替换部分或所有的模式(pattern)匹配项后的新字符串。

(reg: regexp, fn: string | function): string

function replacer(match, p1, p2, p3, offset, string): string
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'

console.log(p.replace('dog', 'monkey'))
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

const regex = /Dog/i
console.log(p.replace(regex, 'ferret'))
// expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"