复杂的正则表达式来分割字符串 [英] Complex regex to split up a string

查看:87
本文介绍了复杂的正则表达式来分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些正则表达式难题的帮助。我仍然要掌握这一切 - 显然不是专家!

I need some help with a regex conundrum pls. I'm still getting to grips with it all - clearly not an expert!

例如。假设我有一个如此复杂的字符串:

Eg. Say I have a complex string like so:

{something:here}{examp.le:!/?foo|bar}BLAH|{something/else:here}:{and:here\\}(.)}

首先,我想通过使用管道将字符串拆分为数组,因此它实际上就像:

First of all I want to split the string into an array by using the pipe, so it is effectively like:

{something:here}{examp.le:!/?foo|bar}BLAH

{something/else:here}:{and:here\\}(.)}

但请注意,大括号内有一个管道要忽略...所以需要为此计算出正则表达式。我最初使用indexOf,但是因为我现在必须考虑在大括号内的管道,所以它使事情变得复杂。

But notice that there is a pipe within the curly brackets to ignore... so need to work out the regex expression for this. I was using indexOf originally, but because I now have to take into account pipes being within the curly brackets, it complicates things.

它还没有结束!然后我还需要通过大括号内的内容将每个字符串拆分成单独的部分而不是。所以我最终得到了2个包含以下内容的数组:

And it isn't over yet! I also then need to split each string into separate parts by what is within the curly brackets and not. So I end up with 2 arrays containing:

Array1

{something:here}
{examp.le:!/?foo|bar}
BLAH

Array2

{something/else:here}
:
{and:here\\}(.)}

我在第一个结束大括号之前添加了一个双斜杠作为一种说法忽略这个。但无法弄清楚正则表达式这样做。

I added a double slash before the first closing curly bracket as a way of saying to ignore this one. But cannot figure out the regex to do this.

任何人都可以帮忙吗?

推荐答案

查找所有出现的字符串在大括号或只是字符串中,然后遍历找到的子串并在遇到管道时拆分。

Find all occurrences of "string in braces" or "just string", then iterate through found substrings and split when a pipe is encountered.

str = "{something:here}{examp.le:!/?foo|bar}BLAH|{something/else:here}:{and:here\\}(.)}"

var m = str.match(/{.+?}|[^{}]+/g)
var r = [[]];
var n = 0;
for(var i = 0; i < m.length; i++) {
   var s = m[i];
   if(s.charAt(0) == "{" || s.indexOf("|") < 0)
       r[n].push(s);
   else {
      s = s.split("|");
      if(s[0].length) r[n].push(s[0]);
      r[++n] = [];
      if(s[1].length) r[n].push(s[1]);
   }
}

此expr可能更适合处理转义大括号

this expr will be probably better to handle escaped braces

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

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

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