📌  相关文章
📜  正则表达式:提取匹配项 - Javascript (1)

📅  最后修改于: 2023-12-03 15:40:38.820000             🧑  作者: Mango

正则表达式:提取匹配项 - Javascript

正则表达式是一种用来匹配文本模式的工具,能够精确地匹配模式中的字符。在 JavaScript 中,可以通过内置的 RegExp 对象使用正则表达式。

RegExp 对象的方法
test()

test() 方法用来测试字符串是否匹配某个模式,返回 true 或 false。

const regex = /hello/;
const text = 'hello world';

const result = regex.test(text);
console.log(result); // true
exec()

exec() 方法用来从文本中提取匹配项,返回一个包含匹配信息的数组,或者返回 null。

const regex = /hello/;
const text = 'hello world';

const result = regex.exec(text);
console.log(result[0]); // hello
匹配模式

正则表达式的匹配模式可以使用一些特殊字符来表示。

普通字符

普通字符直接匹配输入文本中的相应字符。

const regex = /hello/;
const text = 'hello world';

console.log(regex.test(text)); // true
字符类

字符类用方括号 [] 括起来,表示匹配括号中任意一个字符。

const regex = /[aeiou]/;
const text = 'hello world';

console.log(regex.test(text)); // true
范围类

范围类用中括号 [] 括起来,表示匹配括号中的任意一个字符。表示范围的字符用 - 连接。

const regex = /[a-z]/;
const text = 'hello world';

console.log(regex.test(text)); // true
取反类

取反类用中括号 [^] 括起来,表示匹配不在括号中的任意一个字符。

const regex = /[^aeiou]/;
const text = 'hello world';

console.log(regex.test(text)); // false
边界

边界用 ^ 和 $ 表示。

  • ^:匹配文本的开头。
  • $:匹配文本的结尾。
const regexStart = /^hello/;
const regexEnd = /world$/;
const text = 'hello world';

console.log(regexStart.test(text)); // true
console.log(regexEnd.test(text)); // true
量词

量词用来表示重复匹配某个字符或组合。

  • *:匹配 0 次或多次。
  • +:匹配 1 次或多次。
  • ?:匹配 0 次或 1 次。
  • {n}:匹配 n 次。
  • {n,}:匹配 n 次或多次。
  • {n,m}:匹配 n 到 m 次。
const regexZeroOrMore = /wo*/;
const regexOneOrMore = /wo+/;
const regexZeroOrOne = /wo?/;
const regexExact = /wo{2}/;
const regexAtLeast = /wo{2,}/;
const regexBetween = /wo{1,3}/;

console.log(regexZeroOrMore.test('hello world')); // true
console.log(regexOneOrMore.test('hello world')); // true
console.log(regexZeroOrOne.test('hello world')); // false
console.log(regexExact.test('hello world')); // false
console.log(regexAtLeast.test('hello world')); // true
console.log(regexBetween.test('hello world')); // false
总结

以上是正则表达式提取匹配项的基本介绍,需要注意的是正则表达式可以非常复杂,但是灵活运用可以解决很多文本匹配的问题,也是前端开发必备的技能之一。