簡體   English   中英

如何記錄正則表達式本身?

[英]How to document a regular expression in itself?

我有一個正則表達式, 例如在regex101

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

我已驗證它與我的測試字符串匹配

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

由於無法立即理解正則表達式,因此我嘗試使用(?#)進行文檔功能,因此我將正則表達式更改為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#中

您可以使用RegexOptions.IgnorePatternWhitespace或正則表達式開頭的(?x)激活它。

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

這並不是一個理想的解決方案,但是您可以將記錄的正則表達式存儲在String中,並且在匹配之前,可以替換String中的所有\\ r \\ n。

然后,您的代碼中將具有可讀的表示形式,並且在運行時具有正確的正則表達式。

我不知道別的辦法,但是您所擁有的值得稱贊。

問候

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM