如何记录正则表达式本身

本文关键字:正则表达式 记录 何记录 | 更新日期: 2024-09-24 20:54:12

我有一个正则表达式,例如regex101

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

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

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

由于Regex不能立即理解,我尝试了使用(?#)的文档功能,所以我将Regex更改为也在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)

但是现在regex不再匹配我的测试字符串。原因是换行符。将Regex更改为

((?# 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#方法的注释中这样做,因为当regex更改时,这有太多不更新的可能性。

IMHO,最好是在一个有多行的逐字字符串中完成(当然,它仍然必须工作)。

如何记录正则表达式本身

有忽略空白选项

问题是,您将不得不用'转义空格和#。好消息是#将开始一个评论,就像C#中的//一样

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

(?x)由支持https://regex101.com/

这不是一个理想的解决方案,但您可以将文档化的regexp存储在字符串中,并且在匹配之前,您可以替换字符串中的所有regexp。

然后,您将在代码中有一个可读的表示,并在运行时有一个正确的regexp。

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

问候