edwardsmarkf
edwardsmarkf

Reputation: 1417

javascript regex backslash issue

I am attempting to come up with a regex that captures the following:

var testString = "one . one\.two . one\.two\.three" ;
testString.match(/(\\\.)|([^\.\[\]\s]+)/g  );

or perhaps using double-backslashes:

var testString = "one . one\\.two . one\\.two\\.three" ;
testString.match(/(\\\.)|([^\.\[\]\s]+)/g  );

and would yield:

one

one\.two

one\.two\.three

or even better, eliminate the backslashes:

one

one.two

one.two.three

But I am not sure how to look for a period but yet ignore a period that is trailing a backslash.

In other words, i am trying to manually build an object path. if the path looked something like this:

myObject.one.one_two.one_two_three

it would be easy, but my object level-names have period characters in them.
so I am trying to split up a string by periods that are not backslashed.

i hope this makes sense. thank you all very much.

Upvotes: 0

Views: 2598

Answers (1)

trincot
trincot

Reputation: 350252

If you intend the original to have literal backslashes in them, you need to escape them in your literal string notation, like this:

var testString = "one . one\\.two . one\\.two\\.three" ;

I will assume this is what you intended.

If the parts are always separated by space-dot-space, it is easier to just split the string by that.

In case this is not suitable for you (your general pattern is not always like that and/or you really need it to be a regular expression), you can use this variant of your regex:

/(\\\.|[^\s\.\\])+/g

var testString = "one . one\\.two . one\\.two\\.three" ;
console.log('input:', testString);

var result = testString.match(/(\\\.|[^\s\.\\])+/g);

// Show result:
for (var match of result) {
    console.log('output:', match);
}

You can remove the backslashes afterwards with match.replace(/\\\./g, '.') in the above code.

Upvotes: 1

Related Questions