regex to parse string with escaped characters

javascript, regex

Solution

var myregexp = /((?:\\.|[^\\:])*)(?::|$)/g;
var match = myregexp.exec(subject);
while (match != null) {
    for (var i = 0; i < match.length; i++) {
        // Add match[1] to the list of matches
    }
    match = myregexp.exec(subject);
}

Input: `"foo:bar:beer:\\:::1337"`

Output: `["foo", "bar", "beer", "\\:", "", "1337", ""]`

You'll always get an empty string as the last match. This is unavoidable given the requirement that you also want empty strings to match between delimiters (and the lack of lookbehind assertions in JavaScript).

Explanation:

(          # Match and capture:
 (?:       # Either match...
  \\.      # an escaped character
 |         # or
  [^\\:]   # any character except backslash or colon
 )*        # zero or more times
)          # End of capturing group
(?::|$)    # Match (but don't capture) a colon or end-of-string

Problem

I am reading information out of a formatted string. The format looks like this: ``` "foo:bar:beer:123::lol" ``` Everything between the ":" is data I want to extract with regex. If a : is followed by another : (like "::") the data for this has to be "" (an empty string). Currently I am parsing it with this regex: ``` (.*?)(:|$) ``` Now it came to my mind that ":" may exist within the data, as well. So it has to be escaped. Example: ``` "foo:bar:beer:\::1337" ``` How can I change my regular expression so that it matches the "\:" as data, too? Edit: I am using JavaScript as programming language. It seems to have some limitations regarding complex regulat expressions. The solution should work in JavaScript, as well. Thanks, McFarlane

Original source