Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I posted this question a while back which was answered well: Complex regex to split up a string

I know have a new conundrum related to it, and I'm really not getting anywhere...

Say I now have a string like this:

{foo.bar:/?a{3}}{blah}

Using the code supplied in the previous post it does this:

{foo.bar:/?a
{3}}
{blah}

I want it to do this:

{foo.bar:/?a{3}}
{blah}

This is because now I have to deal with strings that don't have an escape before the second curly brace in the example. I need some code that can spot when to ignore certain opening curly braces. Eg. If reading along the string from left to right it sees the first opening curly brace, then when it sees the second opening curly brace it kinda says 'hang on, I haven't seen a valid closing curly brace yet, so I am going to ignore this'. Is this possible? I understand that it may not entirely possible using purely regex.

This is the initial part of the code I am using from the previous question which is causing the issue:

var m = str.match(/{?(\.|[^{}])+}?/g);

Or another solution might be that when the user is typing & submitting the string beforehand, it slips in an escaping backslash without the user seeing it. The trouble with this is knowing which escaping backslashes to 'hide' again from the user...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
207 views
Welcome To Ask or Share your Answers For Others

1 Answer

What about something like this?

var str = "{foo.bar:/?a{3}}hello?{blah}world{blah2}";

var rgx = new RegExp(/}(?!})+[^{]*{/g); 

str = str.replace(rgx,"},{");

//document.write(str + "<br/>");

arr = str.split(",");

for(i=0; i<arr.length; i++) {
    document.write(arr[i] + "<br/>");
}

The key here is the regex /}(?!})+[^{]*{/g

} literal character match

(?!})+ asserts that, following the previous match, at least one } isn't matched.

[^{]* matches any number of characters excluding {

{ literal character match

See it working here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...