Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learn about regular expressions?

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?

like image 935
mowwwalker Avatar asked Aug 08 '26 14:08

mowwwalker


1 Answers

There are various resources:

  • MDC
  • The specification (but that's going to be hard going)
  • JavaScript Kit's intro and reference
  • evolt's Regular Expressions in JavaScript

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
     |||/ \|/ \||
    /(;)(?![";"])/
  1. ( starts a capture group in this case (because the ( isn't followed by ?, =, or ! which change what it does)
  2. ; is a literal, it matches a semicolon
  3. ) ends the capture group
  4. (?! Starts a "negative lookahead" so the overall expression only matches if what's inside the parentheses isn't found after the semicolon
  5. [ begins a character class, which matches any the characters within it
  6. ";" are the characters within the character class. (The second " is redundant.) The character class contains contains ; and ".
  7. ] ends the character class
  8. ) ends the negative lookahead started in #4

So 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.

like image 50
T.J. Crowder Avatar answered Aug 10 '26 12:08

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!