专业的编程技术博客社区

网站首页 > 博客文章 正文

在工作中,常用的正则表达式(三)(正则工具)

baijin 2024-09-03 09:54:52 博客文章 6 ℃ 0 评论

点击右上方红色按钮关注“小郑搞码事”,每天都能学到知识,搞懂一个问题!

一、匹配所有数字

语法:[0-9]或者[\d]

const digitsRegex = /\d/g;
const stringWithDigits = "My cat eats $20.00 worth of food a week.";
stringWithDigits.match(digitsRegex); // ["2", "0", "0", "0"]

二、匹配所有非数字

语法:\D

const nonDigitsRegex = /\D/g;
const stringWithLetters = "101 degrees";
stringWithLetters.match(nonDigitsRegex); // [" ", "d", "e", "g", "r", "e", "e", "s"]

三、匹配空格

语法:\s,用来匹配空格和回车符,注意:非空格就是\S

const sentenceWithWhitespace = "I like cats!"
var spaceRegex = /\s/g;
whiteSpace.match(sentenceWithWhitespace); // [" ", " "]

四、匹配的字符数

语法:{下界,上界}

const regularHi = "hi";
const mediocreHi = "hiii";
const superExcitedHey = "heeeeyyyyy!!!";
const excitedRegex = /hi{1,4}/;
excitedRegex.test(regularHi); // true
excitedRegex.test(mediocreHi); // true
excitedRegex.test(superExcitedHey); //false

五、匹配最低个数的字符数

语法:{下界,},定义最少数量的字符要求。

const regularHi = "hi";
const mediocreHi = "hiii";
const superExcitedHey = "heeeeyyyyy!!!";
const excitedRegex = /hi{2,}/;
excitedRegex.test(regularHi); // false
excitedRegex.test(mediocreHi); // true
excitedRegex.test(superExcitedHey); //false

六、匹配精确的字符数

语法:{requiredCount},指定确切数量

const regularHi = "hi";
const bestHi = "hii";
const mediocreHi = "hiii";
const excitedRegex = /hi{2}/;
excitedRegex.test(regularHi); // false
excitedRegex.test(bestHi); // true
excitedRegex.test(mediocreHi); //false 

七、匹配0次和1次

语法:?

const britishSpelling = "colour";
const americanSpelling = "Color";
const languageRegex = /colou?r/i;
languageRegex.test(britishSpelling); // true
languageRegex.test(americanSpelling); // true


想了解更多正则问题的,这里推荐前面几篇:

正则表达式其实并不难

[值得收藏]工作中常用的正则表达式用法(二)

这十个正则表达式,不仅容易理解,关键是还常用

这篇只用一个实例就讲清楚了正则表达式的所有常用语法

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表