js 正則表達式替換

t="abbbbaa".replace("/(a)/g",function(a,b){console.log(a,b);return "b";})
"abbbbaa"
t="abbbbaa".replace(new RegExp('(a|b)', 'g'),function(a,b){console.log(a,b);return "b";})
VM448:1 a a
4VM448:1 b b
2VM448:1 a a
"bbbbbbb"
t="acdefgbbbbaa".replace(new RegExp('(a|b)', 'g'),function(a,b){console.log(a,b);return "b";})
VM464:1 a a
4VM464:1 b b
2VM464:1 a a
"bcdefgbbbbbb"
t="abbbbaa".replace(/(a)/g,function(a,b){console.log(a,b);return "b";})
3VM506:1 a a
"bbbbbbb"
t="abbbbaa".replace(/[a]/g,function(a,b){console.log(a,b);return "b";})
VM562:1 a 0
VM562:1 a 5
VM562:1 a 6
"bbbbbbb"

Unicode Property Escapes

https://zhuanlan.zhihu.com/p/33353980

元字符 含義
\p{L} 所有字母3
\p{N} 所有數(shù)字,類似于 \d 4
[\p{N}\p{L}] 所有數(shù)字和所有字母换途,類似于 \w 4
\P{L} 不是字母养盗,等價于 [^\p{L}]
\P{N} 不是數(shù)字扫外,等價于 [^\p{N}]
使用方式

var reg1 = /\p{L}/u;
var reg2 = new RegExp(/\p{L}\p{Z}\p{N}/, 'u');


// /\p{Unified_Ideograph}/u  判斷是否中文
/\p{Unified_Ideograph}/u.test('你好') ->true

Unicode Property Escapes是ES2018的功能之一盛正。

基本用法
使用Unicode Property Escapes疮鲫,您可以使用以下簡單正則表達式匹配任何語言的字母:

/\p{Letter}/u
或者用速記焰络,甚至更簡潔:

/\p{L}/u
匹配單詞
關于具體用例(匹配單詞)冲呢,請注意您可以在字符類中使用Unicode Property Escapes鸥咖,從而可以輕松地將字母與其他單詞字符(如連字符)匹配:

/[\p{L}-]/u
將它們拼接在一起燕鸽,您可以將所有[1]種語言中的單詞與這個非常短的RegEx匹配:

/([\p{L}-]+)/ug
示例(從上面的#1答案中無恥地插入):

'Düsseldorf, K?ln, Москва, 北京市, ??????? !@#$'.match(/([\p{L}-]+)/ug)

// ["Düsseldorf", "K?ln", "Москва", "北京市", "???????"]
[1]請注意,我不是語言專家啼辣。 你可能仍然想知道除了字母和連字符之外哪些字符可能是單詞的一部分绵咱。

瀏覽器支持
截至目前(2018年6月),我只能在Chrome(以及其他基于Blink的瀏覽器熙兔,如Opera或Vivaldi)中成功測試此正則表達式悲伶。 然而,ES2018仍然熱銷新聞住涉,所以期待其他現(xiàn)代瀏覽器即將推出麸锉。

我為你做了一個小網站,檢查你的瀏覽器是否支持Unicode Property Escapes舆声。

常規(guī)使用 匹配正則

使用 .test() 方法

let testString = "My test string";  
let testRegex = /string/;  
testRegex.test(testString);

匹配多個模式

使用操作符號 |

const regex = /yes|no|maybe/;

忽略大小寫

使用i標志表示忽略大小寫

const caseInsensitiveRegex = /ignore case/i;  
const testString = 'We use the i flag to iGnOrE CasE';  
caseInsensitiveRegex.test(testString); // true 

提取變量的第一個匹配項

使用 .match() 方法

const match = "Hello World!".match(/hello/i); // "Hello" 

提取數(shù)組中的所有匹配項

使用 g 標志

const testString = "Repeat repeat rePeAT";  
const regexWithAllMatches = /Repeat/gi;  
testString.match(regexWithAllMatches); // ["Repeat", "repeat", "rePeAT"]   

匹配任意字符

使用通配符. 作為任何字符的占位符

// To match "cat", "BAT", "fAT", "mat"  
const regexWithWildcard = /.at/gi;  
const testString = "cat BAT cupcake fAT mat dog";  
const allMatchingWords = testString.match(regexWithWildcard); // ["cat", "BAT", "fAT", "mat"] 

用多種可能性匹配單個字符

使用字符類花沉,你可以使用它來定義要匹配的一組字符 把它們放在方括號里 []

//匹配 "cat" "fat" and "mat" 但不匹配 "bat"  
const regexWithCharClass = /[cfm]at/g;  
const testString = "cat fat bat mat";  
const allMatchingWords = testString.match(regexWithCharClass); // ["cat", "fat", "mat"]   

匹配字母表中的字母

使用字符集內的范圍 [a-z]

const regexWidthCharRange = /[a-e]at/;  
const regexWithCharRange = /[a-e]at/;  
const catString = "cat";  
const batString = "bat";  
const fatString = "fat";  
regexWithCharRange.test(catString); // true  
regexWithCharRange.test(batString); // true  
regexWithCharRange.test(fatString); // false 

匹配特定的數(shù)字和字母

你還可以使用連字符來匹配數(shù)字

const regexWithLetterAndNumberRange = /[a-z0-9]/ig;  
const testString = "Emma19382";  
testString.match(regexWithLetterAndNumberRange) // true 

匹配單個未知字符

要匹配您不想擁有的一組字符,使用否定字符集 ^

const allCharsNotVowels = /[^aeiou]/gi;  
const allCharsNotVowelsOrNumbers = /[^aeiou0-9]/gi;

匹配一行中出現(xiàn)一次或多次的字符

使用 + 標志

const oneOrMoreAsRegex = /a+/gi;  
const oneOrMoreSsRegex = /s+/gi;  
const cityInFlorida = "Tallahassee";  
cityInFlorida.match(oneOrMoreAsRegex); // ['a', 'a', 'a'];  
cityInFlorida.match(oneOrMoreSsRegex); // ['ss'];    

匹配連續(xù)出現(xiàn)零次或多次的字符

使用星號 *

const zeroOrMoreOsRegex = /hi*/gi;  
const normalHi = "hi";  
const happyHi = "hiiiiii";  
const twoHis = "hiihii";  
const bye = "bye";  
normalHi.match(zeroOrMoreOsRegex); // ["hi"]  
happyHi.match(zeroOrMoreOsRegex); // ["hiiiiii"]  
twoHis.match(zeroOrMoreOsRegex); // ["hii", "hii"]  
bye.match(zeroOrMoreOsRegex); // null 

惰性匹配

字符串中與給定要求匹配的最小部分

默認情況下媳握,正則表達式是貪婪的(匹配滿足給定要求的字符串的最長部分)

使用 ? 阻止貪婪模式(惰性匹配 )

 const testString = "catastrophe";  
 const greedyRexex = /c[a-z]*t/gi;  
 const lazyRegex = /c[a-z]*?t/gi;  
 testString.match(greedyRexex); // ["catast"]  
 testString.match(lazyRegex); // ["cat"]  

匹配起始字符串模式

要測試字符串開頭的字符匹配碱屁,請使用插入符號^,但要放大開頭蛾找,不要放到字符集中

const emmaAtFrontOfString = "Emma likes cats a lot.";  
const emmaNotAtFrontOfString = "The cats Emma likes are fluffy.";  
const startingStringRegex = /^Emma/;  
startingStringRegex.test(emmaAtFrontOfString); // true  
startingStringRegex.test(emmaNotAtFrontOfString); // false    

匹配結束字符串模式

使用 $ 來判斷字符串是否是以規(guī)定的字符結尾

const emmaAtBackOfString = "The cats do not like Emma";  
const emmaNotAtBackOfString = "Emma loves the cats";  
const startingStringRegex = /Emma$/;  
startingStringRegex.test(emmaAtBackOfString); // true  
startingStringRegex.test(emmaNotAtBackOfString); // false    

匹配所有字母和數(shù)字

使用\word 簡寫

const longHand = /[A-Za-z0-9_]+/;  
const shortHand = /\w+/;  
const numbers = "42";  
const myFavoriteColor = "magenta";  
longHand.test(numbers); // true  
shortHand.test(numbers); // true  
longHand.test(myFavoriteColor); // true  
shortHand.test(myFavoriteColor); // true

除了字母和數(shù)字娩脾,其他的都要匹配

用\W 表示 \w 的反義

const noAlphaNumericCharRegex = /\W/gi;  
const weirdCharacters = "!_$!!";  
const alphaNumericCharacters = "ab283AD";  
noAlphaNumericCharRegex.test(weirdCharacters); // true  
noAlphaNumericCharRegex.test(alphaNumericCharacters); // false 

匹配所有數(shù)字

你可以使用字符集[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"]

匹配所有非數(shù)字

用\D 表示 \d 的反義

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

匹配空格

使用 \s 來匹配空格和回車符

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

匹配非空格

用\S 表示 \s 的反義

const sentenceWithWhitespace = "C a t"  
const nonWhiteSpaceRegex = /\S/g;  
sentenceWithWhitespace.match(nonWhiteSpaceRegex); // ["C", "a", "t"] 

匹配的字符數(shù)

你可以使用 {下界打毛,上界} 指定一行中的特定字符數(shù)

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 

匹配最低個數(shù)的字符數(shù)

使用{下界, }定義最少數(shù)量的字符要求,下面示例表示字母 i 至少要出現(xiàn)2次

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 

匹配精確的字符數(shù)

使用{requiredCount}指定字符要求的確切數(shù)量

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次

使用 ? 匹配字符 0 次或1次

const britishSpelling = "colour";  
const americanSpelling = "Color";  
const languageRegex = /colou?r/i;  
languageRegex.test(britishSpelling); // true  
languageRegex.test(americanSpelling); // true
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末柿赊,一起剝皮案震驚了整個濱河市俩功,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌碰声,老刑警劉巖诡蜓,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異胰挑,居然都是意外死亡蔓罚,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進店門瞻颂,熙熙樓的掌柜王于貴愁眉苦臉地迎上來脚粟,“玉大人,你說我怎么就攤上這事蘸朋『宋蓿” “怎么了?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵藕坯,是天一觀的道長团南。 經常有香客問我,道長炼彪,這世上最難降的妖魔是什么吐根? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮辐马,結果婚禮上拷橘,老公的妹妹穿的比我還像新娘。我一直安慰自己喜爷,他們只是感情好冗疮,可當我...
    茶點故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著檩帐,像睡著了一般术幔。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上湃密,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天诅挑,我揣著相機與錄音,去河邊找鬼泛源。 笑死拔妥,一個胖子當著我的面吹牛,可吹牛的內容都是我干的达箍。 我是一名探鬼主播没龙,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了兜畸?” 一聲冷哼從身側響起努释,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤碘梢,失蹤者是張志新(化名)和其女友劉穎咬摇,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體煞躬,經...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡肛鹏,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了恩沛。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片在扰。...
    茶點故事閱讀 40,144評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖雷客,靈堂內的尸體忽然破棺而出芒珠,到底是詐尸還是另有隱情,我是刑警寧澤搅裙,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布皱卓,位于F島的核電站,受9級特大地震影響部逮,放射性物質發(fā)生泄漏娜汁。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一兄朋、第九天 我趴在偏房一處隱蔽的房頂上張望掐禁。 院中可真熱鬧,春花似錦颅和、人聲如沸傅事。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽享完。三九已至,卻和暖如春有额,著一層夾襖步出監(jiān)牢的瞬間般又,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工巍佑, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留茴迁,地道東北人萤衰。 一個月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親倦卖。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,092評論 2 355

推薦閱讀更多精彩內容

  • \ :將下一字符標記為特殊字符怕膛、文本熟嫩、反向引用或八進制轉義符。例如褐捻,"n"匹配字符"n"掸茅。"\n"匹配換行符。序列...
    小沙鷹168閱讀 544評論 0 1
  • 將@王者的面具<102292>中的尖括號和尖括號內的id刪除柠逞,將用戶名稱高亮昧狮,并將id在昵稱dom元素的data-...
    FFriday閱讀 2,619評論 0 3
  • 參考原文:http://www.admin10000.com/document/5944.html 一、什么是正則...
    Louis_hey閱讀 853評論 0 1
  • 正則表達式到底是什么東西板壮?字符是計算機軟件處理文字時最基本的單位逗鸣,可能是字母,數(shù)字绰精,標點符號撒璧,空格,換行符茬底,漢字等...
    獅子挽歌閱讀 2,148評論 0 9
  • 一沪悲、正則表達式正則表達式(regular expression)是由一些特定字符以及組合所組成的字符串表達式,用來...
    IIronMan閱讀 1,888評論 0 24