Javascript 正则表达式中 /gi 的含义是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27916055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:53:21  来源:igfitidea点击:

What's the meaning of /gi in a regex?

javascriptregex

提问by batman

I see an line in my JavaScript code like this:

我在 JavaScript 代码中看到这样一行:

var regex = /[^\w\s]/gi;

What's the meaning of this /giin the regex?

/gi在正则表达式中是什么意思?

Other part I can understand as it accepts a group of word and spaces, but not /gi.

其他部分我可以理解,因为它接受一组单词和空格,但不接受/gi.

回答by vks

g modifier: global. All matches (don't return on first match)

i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

In your case though iis immaterial as you dont capture [a-zA-Z].

在您的情况下,虽然i不重要,因为您没有捕获[a-zA-Z].

For input like !@#$if gmodifier is not there regex will return first match !See here.

对于像!@#$ifg修饰符不存在这样的输入,正则表达式将返回第一个匹配项,!请参见此处

If gis there it will return the whole or whatever it can match.See here

如果g在那里,它将返回整个或它可以匹配的任何内容。看这里

回答by elixenide

The beginning and ending /are called delimiters. They tell the interpreter where the regex begins and ends. Anything afterthe closing delimiter is called a "modifier," in this case gand i.

开头和结尾/称为分隔符。它们告诉解释器正则表达式的开始和结束位置。结束定界符之后的任何内容都称为“修饰符”,在本例中为gi

The gand imodifiers have these meanings:

gi改性剂具有以下含义:

  • g= global, match all instances of the pattern in a string, not just one
  • i= case-insensitive (so, for example, /a/iwill match the string "a"or "A".
  • g= global,匹配字符串中模式的所有实例,而不仅仅是一个
  • i= 不区分大小写(例如,/a/i将匹配字符串"a""A".

In the context you gave (/[^\w\s]/gi), the iis meaningless, because there are no case-specific portions of the regex.

在您提供 ( /[^\w\s]/gi)的上下文中, thei是没有意义的,因为正则表达式没有特定于大小写的部分。