我想到了一個例子,我可以用來很好地學習它。我設計了一種我想要決議和解釋的“腳本語言”(作為字串)。
PS:是的,它有點讓人想起 LINQ,但這只是一個巧合。
我首先想到的是,我想洗掉所有評論,因為這些不應該被解釋。
我只尋找以下評論:/*...*/和//...\n
但是,這些當然不應該出現在引號內:"..."和'...'
但是如何使用 RegEx 查找不在引號內的評論?
細繩:
//get means only read, but not to mutate data
Get(BooksWithAuthors)
//default queries via mycel
.Query()
//junction table to pair books and authors
.From(BookAuthor.As(BA))
//main table for books
.Join(left: Books.As(B) => B.Id == BA.BookId)
//main table for authors
.Join(left: Authors.As(A) => A.Id == BA.AuthorId)
//groups by column, body allows to restore data (restructuring)
.GroupBy(B.Id, => B.Authors.Add(A))
//ignore still registerd data objects for the response
.SelectIgnore(BA)
//or select only that fields or objects you want to response
.Select(B)
.Foo("//wrong-comment-inside-quotes")
.Foo('//wrong-comment-inside-single-quotes')
.Foo('some /*wrong-comment*/ inside')
;
//get means only read, but not to mutate data
Get(BooksWithAuthorsByMethod)
//using individual backside methods (created by own)
.GetBooksWithAuthors(id:6, filter:{key:'minAuthorAge', value:17})
;
/*
comments
"over"
'multiply
lines' //with wrong comments inside
*\
正則運算式:
.*[^'"].*([\/]{2}.*[\r\n|\r|\n]).*[^'"].*
(https://regex101.com/r/zPzBFj/1)
是的,我只用 嘗試過//,但并不是所有的事件都被發現,而且它也與引號內的注釋相匹配。也許?!不是正確的方法。但我該怎么做呢?
我相信我會對這個例子還有一兩個問題。但正如我所說,我還在學習 RegEx,所以一步一步來......
uj5u.com熱心網友回復:
如果將字串與正則運算式匹配
/'.*?'|".*?"|(\/\/[^\r\n]*|\/\*.*?\*\/)/gs
評論將保存到捕獲組 1。這個想法是匹配但不捕獲您不想要的內容,并匹配并捕獲您想要的內容。不要注意未捕獲的匹配項。
沒有DOTALL標志 ( /s) 句點匹配除行終止符以外的所有字符;使用該標志設定句點匹配所有字符,包括行終止符。
演示
在演示鏈接中,未捕獲的匹配項(不是評論,因此忽略)顯示為藍色,而捕獲的匹配項(評論)顯示為綠色。
正則運算式可以分解如下。
'.*?' # match a single-quote followed by >= 0 chars, lazily,
# followed by a single-quote
| # or
".*?" # match a double-quote followed by >= 0 chars, lazily,
# followed by a double-quote
| # or
( # begin capture group 1
\/\/ # match '//'
[^\r\n]* # match >= 0 chars other than line terminators
| # or
\/\* # match '/*'
.*? # match >= 0 chars, lazily
\*\/ # match '*/'
) # end capture group 1
這是一個如何作業的示例。假設字串如下。
A dog "is // a\nman's" /* best */ 'friend /* so it */ is' // said
正則運算式引擎執行以下步驟。
- 匹配失敗
A。 之后不匹配,A然后不匹配d,和。og- 匹配但不捕獲
"is // a\nman's"。1 - 匹配失敗
。 - 匹配并捕獲評論
/* best */。 - 匹配失敗
。 - 匹配但不捕獲
'friend /* so it */ is'。 - 匹配失敗
。 - 匹配并捕獲評論
// said
1. 在這個匹配之后,正則運算式引擎的字串指標位于剛剛匹配的(最后一個)雙引號和后面的空格之間。
uj5u.com熱心網友回復:
這將回傳您在示例中尋找的內容,如果您發現任何邊緣情況,請告訴我。您必須根據是注釋還是參考字串對匹配項進行后處理。
(?:(?:(\/)(\*)|(["'])).*?(?:\2\1|\3))|(?:\/\/[^\n] )
https://regex101.com/r/uqx1cJ/1
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/465779.html
標籤:javascript C# 。网 正则表达式
