使用正则表达式解析转义字符 [英] Parsing for escape characters with a regular expression

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

问题描述

我正在创建一个逗号分隔的脚本来存储项目的各种数据。

I'm creating a comma-separated script to store various pieces of data for a project.

我的数据行的最后一部分总是前面的数据的汇总(它总是除换行符之外的任何字符的字符串)。问题是,我沿着逗号分割整行,因此如果该行的摘要部分中有逗号,那么超出逗号之后的任何内容都会被拆分,我不想要。

The last part of my data line is always a summary of the preceding data (it is always a string of any character except newline characters). The problem is that I split the entire line along the commas, so if this summary portion of the line has commas in it, anything after the excess commas will be split as well, which I don't want.

所以我想为逗号做自己的转义字符。我认为最容易出错的方法是使用正则表达式。

So I'd like to make my own escape character for commas. I figure that the least error-prone way to do this is with regular expressions.

我想出了以下表达式: ^,(?! \\)$ 我希望会寻找逗号,但不是逃脱的逗号。不幸的是,它没有工作。

I've come up with the following expression, ^,(?!\\,)$ which I had hoped would look for commas, but not escaped commas. Unfortunately, it did not work.

以下两行说明了我的数据是如何分隔的。

The following two lines illustrate how my data is separated.

01, 0, 80.0, 0x00100204, 0x00000000, 0x00000800, 0xFFFFF800, 0.02, 0.5, Channel 01: Voltage Offset\,\,\,comma 
02, 0, 80.0, 0x00100208, 0x00000000, 0x00000800, 0xFFFFF800, 0.02, 0.5, Channel 02: Voltage Offset

请注意,在第一行数据,我在其中有多余的逗号,表示为 \,\,\,comma

Note that in the first line of data, I have excess commas in there, denoted by \,\,\,comma

但是当我调用 Regex.Split(line,@^,(?! \,)$); ,没有什么发生,数组包含我的整个字符串。

But when I call Regex.Split(line, @"^,(?!\,)$");, nothing happens, I just get a single element array containing my entire string.

推荐答案

这是一个很好的例子使用负的lookbehind:

This is a good example to use negative lookbehind:

(?<!\\),

工作演示

Working demo

>

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

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