Character set in regex

Character set in regex
0.0 0

#1

hello

why does this code matches both \W and _ if it is inside a character set [] ?

does’t s character set matches this or that but never 2 things?

var str = "fdfd.////__/f";
          
console.log(str.replace(/[\W_]/gi,""); // will replace both \W and _
        


#2

It is only matching one at a time, but because you are using the greedy flag, it will match multiple times.


#3

What are wanting to do with regex?


#4

@ArielLeslie
It is actually a global flag not greedy.

@tomer-n
https://regex101.com/r/FPqRIC/1
hope this helps answers your question


#5

i want to find everything that is not words and underscores _ .

i want to replace them with “” with the replace method.
what i don’t understand is why it matches this \W and this _ if it is inside brackets []

I thought that brackets find one thing at a time only.


#6

They do (only match one character), just reread what was already written and check out thisiswhale’s link, where you’ll have the matching coloured.

g means repeat, if that makes it easier to understand.

What string output did you expect? What you describe matches your code …


#7

hey @lynxlynxlynx,

doesn’t g means global? also the regex website says it doesn’t return after a match.

image


#8

the output is fine. I just try to understand what happened…


#9

Of course it stands for global … And because it doesn’t stop after the first match, it repeats the match after each substitution, checking if there’s still anything to do — until it reaches the end of the input string. IOW it’s killing the bad characters one at a time.


#10

thanks mate i got it


#11

Tomato toh-mah-toh, depending on the context you learned regular expressions in.


#12

It’s most useful/least ambiguous to refer to the g flag as “global”, because:

  • “Greedy” already stands for a different concept in regexes
  • The same is true of “repeat”

For example, the regex /(ab){5}/ matches 5 “ab” substrings in a row (i.e. the substring must repeat 5 times). If we change it to /(ab){1,5}/, it matches as many as it can up to 5 (i.e. it’s greedy).