正则表达式.NET拆分 [英] regex .net split

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

问题描述

我可以分割字符串为两个基础上2位:

I can split a string into two based on 2 spaces:

string Line = "1  2";

Regex.Split(Line, "  ");

=> 1,2

=> 1, 2

我想补充一个例外。仅当如本例所示'通过[]未括'分割

I would like to add an exception. Only split if 'not enclosed by [ ]' as shown in this example.

string Line = "1  2  [1  2]";

Regex.Split(Line, "  ");

=> 1,2,[1 2]

=> 1, 2, [1 2]

我可以很轻松地通过正则表达式实现这一目标?顺便说一句,我用.NET。

Can I fairly easily achieve this via regex? By the way, I use .NET.

推荐答案

您可以使用一个前瞻,断言没有结束] 下一开幕之前 [或字符串的结尾:

You could use a lookahead, that asserts that there is no closing ] before the next opening [ or the end of the string:

Regex.Split(Line, @"[ ]+(?![^\[\]]*\])");

这将失败你,如果你有嵌套 [...] 结构虽然。需要注意的是超前是不实际的比赛的一部分,它只检查接下来无需消耗任何东西。里面的前瞻我用 [^ \ [\] 这是一个否定的字符类,除了匹配任何类型的括号中的任何字符。

This will fail you if you have nested [...] structures though. Note that the lookahead is not part of the actual match, it just checks what follows without consuming anything. Inside the lookahead I used [^\[\]] which is a negated character class, matching any character except for any kind of square bracket.

另外请注意,这种分裂在1个或多个空格。如果你想需要至少两个,替换 [] + [] {2} ,如果你想整整两个与 [] {2}

Also note that this splits on 1 or more spaces. If you want to require at least two, replace [ ]+ with [ ]{2,} and if you want exactly two with [ ]{2}.

进一步阅读lookarounds。

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

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