逃避星号抢错字符 [英] Escaping Asterisk Grabs wrong character

查看:54
本文介绍了逃避星号抢错字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行下面的代码时,我得到了意外的结果,其中 \ * 也捕获了É.有没有办法让它像我想要的那样只捕获 * ?

When I run the code below I get the unexpected result where \* also captures É. Is there a way to make it only capture * like I wanted?

let s =
    "* A

ÉR

* B"
let result = System.Text.RegularExpressions.Regex.Replace(s, "\n(?!\*)", "", Text.RegularExpressions.RegexOptions.Multiline)
printfn "%s" result

运行替换后的结果

* AÉR
* B

预期结果

"* A

ÉR
* B"

更新

当我使用 \ n(?= \ *)这样的模式时,这似乎起作用.我想我需要正向超前.

This seems to be working, when I use a pattern like so \n(?=\*). I guess I needed a positive lookahead.

推荐答案

您说对了,您需要使用正向先行而不是负向先行来获得所需的结果.但是,为了澄清注释中出现的问题,在F#中以" 分隔的字符串与以" 分隔的普通C#字符串或一个由 @" 分隔的C#字符串-如果要使用后者,则还应该在F#中使用 @" .区别在于,在正常的F#字符串中,反斜杠在用于有效字符转义的情况下仅被用作转义序列 (请参见字符串.

You're right that you need to use positive lookahead instead of negative lookahead to get the result you want. However, to clarify an issue that came up in the comments, in F# a string delimited by just "" is not quite like either a plain C# string delimited by "" or a C# string delimited by @"" - if you want the latter you should also use @"" in F#. The difference is that in a normal F# string, backslashes will be treated as escape sequences only when used in front of a valid character to escape (see the table towards the top of Strings (F#)). Otherwise, it is treated as a literal backslash character. So, since '*' is not a valid character to escape, you luckily see the behavior you expected (in C#, by contrast, this would be a syntax error because it's an unrecognized escape). I would recommend that you not rely on this and should use a verbatim @"" string instead.

换句话说,在F#中,以下三个字符串都是等效的:

In other words, in F# the following three strings are all equivalent:

let s1 = "\n\*"
let s2 = "\n\\*"
let s3 = @"
\*"

我认为C#设计更明智,因为它避免了对确切逃脱的混淆.

I think that the C# design is more sensible because it prevents confusion on what exactly is being escaped.

这篇关于逃避星号抢错字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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