Expaination about regex

Expaination about regex
0

#1

Hello, i created a regex but i don’t really now how i did it. I must be luck.
Here the regex: /^[\s"’]+|(?!^)/gi;
Could i have an explaination ?
I used it for this exercice:
https://beta.freecodecamp.org/en/challenges/intermediate-algorithm-scripting/convert-html-entities

I wanted to split but don’t delete the splited value of special characters (space, single quote and double quote with <>)

Thx


#2

This link can help you to see what regular expression means:


#3

^ means “starts with”.
\s means any whitespace character (space, tab, return etc).
" and ’ literally mean those characters: double-quote and single quote.
The + qualifier means “one or more”.

So, the first part of the expression (^[\s"’]+) says: match any string that starts with a whitespace character, a double quote, or a single quote, and that is composed entirely of the characters in this set.

The pipe character | is an “OR” operator. It makes it so your expression will match any string that meets criteria before it, or any string that meets criteria after it: (?!^). (?!) is called a negative lookahead, and it prevents a string from being matched if it’s followed by whatever follows the negative lookahead. So for example abcd(?!e) would match a string “abcd” as long as it’s not followed by “e”. In your case, negative lookahead (?!^) is not preceded by anything, so it matches any empty string as long as it’s not followed by start of a string. the “gi” in the end are “global” and “insensitive” flags and they specify that your expression should match all instances (rather than just first match) and that it should ignore case (not actually relevant to your expression since you’re not matching any letters). It’s all a little confusing, but there is a fantastic site for learning regular expressions:

https://regex101.com/

You can test your expressions there, see what they match, and it even gives explanations for various parts of your epxression.


#4

Thx your very much for the explaination !


#5

Sure thing! Glad to help.