MrIzik
MrIzik

Reputation: 139

Javascript Regular Expression excluding a word

i am familiar with javascript regular expression to not match a word but it does not help me much. when given a string (with any type of characters), i wish to parse it around two tokens, "//" and "\\". i did the following:

var patt = /.*[^"//"]/gm;
patt.exec(str);

but it seems to match any occurrences of the characters between the quotes, i.e. "/" and "//". how may i achieve it?

Upvotes: 0

Views: 311

Answers (2)

Borodin
Borodin

Reputation: 126722

How about simply

var tokens = str.split(/\/\/|\\\\/);

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074305

When you start a character class with ^ (as you have in [^"//"]), it means "any character except the ones listed." So [^"//"] means "match one of any character except " and / (it ignores the fact you've listed each of them twice).

If you're trying to match the text between two slashes (//) and one backslash (\) (as per your question; you later made a comment suggesting it's two backslashes, I address that later), then:

var match = str.match(/\/\/(.*?)\\/);    // Match between // and \

Note that we have to escape the slashes because the slash is the regular expression delimiter; and we have to escape backslashes because the backslash is the escape character.

The above means "match two slashes followed by zero or more of any character followed by a backslash." The ? after * makes * non-greedy (so it will consume as few characters as it can to satisfy the expression). The () create a capture group, which in the match object will receive the characters that matched in that position.

Example:

test("foo");
test("foo //bar");
test("foo //bar\\");
test("foo //bar\\ baz");
test("bar\\ baz");
test("//bar\\ baz");
test("foo //bar\\ baz \\ more \\ more");

function test(str) {
    var m = str.match(/\/\/(.*?)\\/),
        cap = (m && m[1]) || "<em>nothing</em>";
    display("Str: <code>" + str + "</code>: Captured <code>" + cap + "</code>");
}

Output:

Str: foo: Captured nothing

Str: foo //bar: Captured nothing

Str: foo //bar\: Captured bar

Str: foo //bar\ baz: Captured bar

Str: bar\ baz: Captured nothing

Str: //bar\ baz: Captured bar

Str: foo //bar\ baz \ more \ more: Captured bar

Live copy

Or for two backslashes:

var match = str.match(/\/\/(.*?)\\\\/);  // Match between // and \\

Live copy (the output is the same, just with two backslashes)

Some reading on JavaScript regular expressions:

Upvotes: 3

Related Questions