复杂的正则表达式以拆分字符串-第2部分 [英] Complex regex to split up a string - Part 2

查看:96
本文介绍了复杂的正则表达式以拆分字符串-第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}

我希望它这样做:

{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...

推荐答案

这样的事情怎么办?

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/>");
}

这里的关键是正则表达式/}(?!})+[^{]*{/g

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

}文字字符匹配

(?!})+断言,在上一次匹配之后,至少一个}不匹配.

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

[^{]*匹配除{

{文字字符匹配

此处.

这篇关于复杂的正则表达式以拆分字符串-第2部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆