简体   繁体   English

RegEx:使用/ i vs. / g(/ g替换空格但/ i不替换)

[英]RegEx: Using /i vs. /g (/g replaces whitespace but /i doesn't)

I want an array containing only letters (I'm writing a function to check for pangrams). 我想要一个只包含字母的数组(我正在编写一个函数来检查pangrams)。 Using this code with /g gives me an array of only letters and no spaces ( lettersArr.length = 34 ): 使用/g代码给我一个只有字母和没有空格的数组( lettersArr.length = 34 ):

var s = "The quick brown fox jumps over the lazy dog."
var lettersArr = s.replace(/[^a-z]+/i, "").split("");
console.log(lettersArr);

However, using the same code with /i gives me an array containing the letters as well the space between quick and brown ( lettersArr.length = 43 ). 但是,使用与/i相同的代码给出了一个包含字母的数组以及快速和棕色之间的空格( lettersArr.length = 43 )。 Since /i is just case-insensitive, shouldn't they give the same results? 既然/i只是不区分大小写,那么它们不应该给出相同的结果吗? Is this just a RegEx or Javascript bug? 这只是一个RegEx或Javascript错误吗?

You didn't add the g flag to the regex, so it's only replacing the first match, in your case the first space character. 你没有将g标志添加到正则表达式,所以它只替换第一个匹配,在你的情况下是第一个空格字符。

If you add the g flag, it works: 如果你添加g标志,它的工作原理是:

var s = "The quick brown fox jumps over the lazy dog."
var lettersArr = s.replace(/[^a-z]+/gi, "").split("");
console.log(lettersArr);

Using the g flag means that .replace won't stop at the first match. 使用g标志意味着.replace不会在第一场比赛时停止。

Note that without i the array should be of length 35, and with i 34, so I'm not sure how you're getting 26 or 28. 请注意,如果没有i ,阵列的长度应为35,而使用i 34,所以我不确定你是如何获得26或28的。

/[^az]+/i Matches [space][.] First Match which is [space] /[^az]+/i匹配[空格] [。] 第一场比赛[空间]

When you do 当你这样做

   s.replace(/[^a-z]+/i, "")

gives 'Thequick brown fox jumps over the lazy dog.' 'Thequick brown fox jumps over the lazy dog.' length = 43


/[^az]+/g [T][space][.] Matches Globally /[^az]+/g [T] [space] [。] 匹配全球

Capital T is missing here 这里缺少Capital T.

gives "hequickbrownfoxjumpsoverthelazydog" length = 34 给出"hequickbrownfoxjumpsoverthelazydog" length = 34


So you need to use both flags because you want to match capital T too. 所以你需要使用两个标志,因为你也想匹配大写字母T.

/[^az]+/gi [space][.] Matches globally case insensitive /[^az]+/gi [space] [。] 匹配全局不区分大小写

s.replace(/[^az]+/gi, "")

Gives the desired string 提供所需的字符串

"Thequickbrownfoxjumpsoverthelazydog" length = 35 "Thequickbrownfoxjumpsoverthelazydog" length = 35

Afterwards you can split it. 之后你可以拆分它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM