Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I see an line in my JavaScript code like this:

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

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

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

like image 638
batman Avatar asked Jan 13 '15 06:01

batman


People also ask

What does GI mean regex?

The gi modifier is used to do a case insensitive search of all occurrences of a regular expression in a string.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

What is ?: In regex Javascript?

The difference between ?: and ?= is that ?= excludes the expression from the entire match while ?: just doesn't create a capturing group. So for example a(?:b) will match the "ab" in "abc", while a(?=

What does G flag do?

(debug) Inserting the `g' flag tells the compiler to insert more information about the source code into the executable than it normally would. This makes use of a debugger such as gdb much easier, since it will be able to refer to variable names that occur in the source code.


Video Answer


2 Answers

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 i is immaterial as you dont capture [a-zA-Z].

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

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

like image 161
vks Avatar answered Oct 05 '22 08:10

vks


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

The g and i modifiers have these meanings:

  • g = global, match all instances of the pattern in a string, not just one
  • i = case-insensitive (so, for example, /a/i will match the string "a" or "A".

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

like image 23
elixenide Avatar answered Oct 05 '22 07:10

elixenide