In an answer to one of my questions, someone had posted:
// could replace it with an easier to work with delimiter
str.replace(/(;)(?![";"])/g, '|')
// or split it, but skip over results that are just a ;
var strArr = str.split(/(;)(?![";"])/);
for (s in strArr) {
if (strArr[s] !== ";") {
// do something with strArr[s]
console.log(strArr[s]);
}
}
I'm completely lost at /(;)(?![";"])/. It looks like a bunch of random symbols to me :( .
Where can I learn more about regular expression syntax?
There are various resources:
Regarding the actual expression, the / characters mark the beginning and end of the regular expression literal (like quotes do for a string, although the ending / may be followed by flags), and then:
+------------- 1
|+------------ 2
||+----------- 3
||| +--------- 4
||| |
||| |
||| | +------- 5
||| | | +----- 6
||| | | | +--- 7
||| | | | |+-- 8
|||/ \|/ \||
/(;)(?![";"])/
( starts a capture group in this case (because the ( isn't followed by ?, =, or ! which change what it does); is a literal, it matches a semicolon) ends the capture group(?! Starts a "negative lookahead" so the overall expression only matches if what's inside the parentheses isn't found after the semicolon[ begins a character class, which matches any the characters within it";" are the characters within the character class. (The second " is redundant.) The character class contains contains ; and ".] ends the character class) ends the negative lookahead started in #4So in all, match (and capture) a semicolon provided it's not followed immediately by a quote or semicolon. I can't see any particular reason for capturing the semicolon, but perhaps there was a reason in the context of the question where this was recommended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With