如何记录正则表达式本身?

问题描述 投票:1回答:2

我有一个正则表达式e.g. at regex101

(\/+[^\/\[\]]+(?:\[[^\]']*(?:'[^']*')\])?)+

我已经验证它与我的测试字符串匹配

//SapButton[@automationId='tbar[0]/btn[15]']

由于无法立即理解正则表达式,我使用(?#)尝试了文档功能,因此我将正则表达式更改为also at regex101

((?# Capturing group for the type name)
\/+(?# Start with / or // )
[^\/\[\]]+(?# Type name exclusing start of attribute and next type)
(?:(?# Non-capturing group for the attribute)
\[(?# Start of an attribute)
[^\]']*(?# Anything but end of attribute or start of string)
(?:(?# non-capturing group for string)
'(?# string start)
[^']*(?# anything inside the string, except end of string)
'(?# string end)
)(?# end of string group)
\](?# end of attribute)
)?(?# Attribute can occur 0 or one time)
)+(?# Type can occur once or many times)

但现在正则表达式不再匹配我的测试字符串了。原因是换行。将正则表达式更改为

((?# Capturing group for the type name)\/+(?# Start with / or // )[^\/\[\]]+(?# Type name exclusing start of attribute and next type)(?:(?# Non-capturing group for the attribute)\[(?# Start of an attribute)[^\]']*(?# Anything but end of attribute or start of string)(?:(?# non-capturing group for string)'(?# string start)[^']*(?# anything inside the string, except end of string)'(?# string end))(?# end of string group)\](?# end of attribute))?(?# Attribute can occur 0 or one time))+(?# Type can occur once or many times)

作品。但它再次难以理解。

如何正确记录正则表达式?

请注意,我希望避免在C#方法的注释中执行此操作,因为在更改正则表达式时,这有太多可能无法更新。

恕我直言,最好用多行的逐字字符串完成(当然,它仍然必须工作)。

c# regex
2个回答
2
投票

Ignore White Space option

问题是,你必须用#逃离空间和\。好消息是#将开始发表评论,比如C#中的//

您可以在正则表达式的开头用RegexOptions.IgnorePatternWhitespace(?x)激活它。

(?x)得到了https://regex101.com/的支持


0
投票

它不是一个理想的解决方案,但您可以将记录的正则表达式存储在String中,在匹配之前,您可以替换String中的所有\ r \ n。

然后,您将在代码中具有可读表示,并在运行时具有正确的正则表达式。

我不知道其他方式,但你所拥有的是值得称赞的。

问候

© www.soinside.com 2019 - 2024. All rights reserved.