本文介绍了如何使用正则表达式将字符串拆分为“,",除非“,"在括号内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以帮我解决这样的字符串的正则表达式吗?:

Can anyone help me out with a regular expression for a string such as this?:

[Header 1], [Head,er 2], Header 3

这样我就可以把它分成几块:

so that I can split this into chunks like:

[标题 1]
[Head,er 2]
标题 3

我已经做到了:

(?<=,|^).*?(?=,|$)

哪个会给我:

[标题 1]
[头部
,er 2]
标题 3

推荐答案

在这种情况下,在分隔符(逗号)上进行拆分比在标记(或块)上进行拆分更容易.识别作为分隔符的逗号需要一个相对简单的前瞻:

In this case it's easier to split on the delimiters (commas) than to match the tokens (or chunks). Identifying the commas that are delimiters takes a relatively simple lookahead:

,(?=[^\]]*(?:\[|$))

每次您找到一个逗号时,您都会对三件事中的一件进行前瞻.如果您首先找到一个右方括号,则逗号位于一对括号内,因此它不是分隔符.如果您找到左括号或行/字符串的结尾,则它是一个分隔符.

Each time you find a comma, you do a lookahead for one of three things. If you find a closing square bracket first, the comma is inside a pair of brackets, so it's not a delimiter. If you find an opening bracket or the end of the line/string, it's a delimiter.

这篇关于如何使用正则表达式将字符串拆分为“,",除非“,"在括号内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:21