Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

javascript - Complex regex to split up a string - Part 2

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...