正则表达式解析带有转义字符的字符串 [英] regex to parse string with escaped characters

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

问题描述

我正在从格式化的字符串中读取信息。
格式如下:

I am reading information out of a formatted string. The format looks like this:

"foo:bar:beer:123::lol"

:之间的所有内容都是我想用正则表达式提取的数据。如果a:后面是另一个:(比如::),这个数据必须是(空字符串)。

Everything between the ":" is data I want to extract with regex. If a : is followed by another : (like "::") the data for this has to be "" (an empty string).

目前我正在解析它使用此正则表达式:

Currently I am parsing it with this regex:

(.*?)(:|$)

现在我想起数据中也可能存在:。所以它必须被逃脱。
示例:

Now it came to my mind that ":" may exist within the data, as well. So it has to be escaped. Example:

"foo:bar:beer:\::1337"

如何更改正则表达式以使其与\:匹配作为数据呢?

How can I change my regular expression so that it matches the "\:" as data, too?

编辑:我使用JavaScript作为编程语言。它似乎对复杂的规则表达有一些限制。该解决方案也适用于JavaScript。

I am using JavaScript as programming language. It seems to have some limitations regarding complex regulat expressions. The solution should work in JavaScript, as well.

谢谢,
McFarlane

Thanks, McFarlane

推荐答案

var myregexp = /((?:\\.|[^\\:])*)(?::|$)/g;
var match = myregexp.exec(subject);
while (match != null) {
    for (var i = 0; i < match.length; i++) {
        // Add match[1] to the list of matches
    }
    match = myregexp.exec(subject);
}

输入:foo:bar:beer:\\ \\\ ::: 1337

输出: [foo,bar,beer ,\\:,,1337,]

你总是得到一个空字符串最后一场比赛。这是不可避免的,因为要求您还希望空字符串在分隔符之间匹配(以及JavaScript中缺少lookbehind断言)。

You'll always get an empty string as the last match. This is unavoidable given the requirement that you also want empty strings to match between delimiters (and the lack of lookbehind assertions in JavaScript).

说明:

(          # Match and capture:
 (?:       # Either match...
  \\.      # an escaped character
 |         # or
  [^\\:]   # any character except backslash or colon
 )*        # zero or more times
)          # End of capturing group
(?::|$)    # Match (but don't capture) a colon or end-of-string

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

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