简体   繁体   English

C#中的转义字符

[英]Escape character in c#

I stuck in escape sequence in program. 我在程序中陷入了转义序列。

I am getting input from xml file in single quotes. 我从单引号的xml文件中获取输入。

So in string it may contain any escape sequence. 因此,在字符串中,它可以包含任何转义序列。

So what I want to do is consider next character after escape character as normal character. 所以我想做的是将转义字符后的下一个字符视为普通字符。

Example: '\abc\\t'
 Output: 'abc\t'

So for that I created regular expression which is: 为此,我创建了以下正则表达式:

Regex.Replace(SearchString, @"\\?(?<Character>)", "${Character}");

But it replaces all escape character and gives output : 但是它将替换所有转义字符并提供输出:

abct

Please help me how can I do it? 请帮我怎么办?

The named group in your regular expression matches nothing, so it does the same as Replace(@"\\", "") . 正则表达式中的命名组不匹配任何内容,因此与Replace(@"\\", "")

Match one character in the group: 匹配组中的一个字符:

SearchString = Regex.Replace(SearchString, @"\\(.)", "$1");

尝试这个:

Regex.Replace(SearchString, @"\\(?<Character>[^\\])", "${Character}");

Basically, you need parse your string character by character. 基本上,您需要逐字符分析字符串。 Pseudo-code: 伪代码:

Loop through all characters c:
    If c is escape character:
        Read next character and do something special (\t is tab, \\ is backslash, ...)
    Else:
        Copy character to output

What if you do like: 如果您喜欢:

SearchString = SearchString.Replace(@"\\", @"\");

It would give: 它会给:

\abc\t

Here escaped \\t is now treated as a "tab character". 此处转义的\\t现在被视为“制表符”。

It is what you are looking for ? 这是您要找的东西吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM