Reputation: 69
I need to split a string like this, on dot. But I don't want to split on dot that are inside of a string (' or "). I'm not parsing a file; just a simple string with no line breaks.
part 1;"12:'[email protected]'.8:'23'.25:'hello'.6:6"
Result should be:
part 1 "12:'[email protected]'"
part 2 "8:'23'"
part 3 "25:'hello'"
part 4 "6:6"
I suppose this can be done with a regex but if not; I'm open to another approach.
EDIT
I have
str = "12:'[email protected]'.8:'23'.25:'hello'.6:6"
and I expect to get
str[0]=12:[email protected] str[1]=8:'23'
str[2]=25:'hello'
str[3]=6:6
but whenever i split it, it shows like that:
str[0]=12:xyz@gmail
str[1]=com
str[2]=8:'23'
str[3]=25:'hello'
str[4]=6:6
Upvotes: 1
Views: 88
Reputation: 11032
I am not sure about split, but you can use replace
like this (prone to catastrophic backtracking)
((?:(?:'[^']+')*[^.']*)*)(?:\.|$)
JS Code
var re = /((?:(?:'[^']+')*[^.']*)*)(?:\.|$)/g;
var str = '\'1.2\':\'[email protected]\'.8:\'2.3\'.25:\'he.llo\'.6:6\'1.2\''
document.writeln("<pre>" + str.replace(re, "$1\n") + "</pre>");
Upvotes: 2
Reputation: 626870
You can match with the following regex:
/[^.']+(?:'[^']*')?/g
See the regex demo
Details:
[^.']+
- 1 or more characters other than '
and .
(?:'[^']*')?
- an optional '...'
string ('
followed with 0+ characters other than '
followed with a '
.Depending on what the content can be, you can use an enhanced version:
/[^.']*(?:'[^']*'[^.']*)*/g
See another demo
Demo 1 (simplified):
var re = /[^.']+(?:'[^']*')?/g;
var str = '12:\'[email protected]\'.8:\'23\'.25:\'hello\'.6:6';
var m = str.match(re);
document.body.innerHTML = "<pre>" + JSON.stringify(m, 0, 4) + "</pre>";
Demo 2 (if the contents are more complex):
var re = /[^.']*(?:'[^']*'[^.']*)*/g;
var str = '\'1.2\' 12:\'[email protected]\'.8:\'23\'.25:\'hello\'.6:6';
var res = [];
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
if (m[0]) { res.push(m[0]);}
}
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>";
Upvotes: 3