在分析ASCII 影像或地圖時,可能會出現以下情況識別特定模式變得必要。其中一個圖案是由三個 X 組成的垂直線。使用正規表示式,可以有效解決此任務。
確定是否存在垂直線如果存在三個X 的形成,則可以使用以下正規表示式:
(?xm) # ignore comments and whitespace, ^ matches beginning of line ^ # beginning of line (?: . # any character except \n (?= # lookahead .*+\n # go to next line ( ?+ . ) # add a character to the 1st capturing group .*+\n # next line ( ?+ . ) # add a character to the 2nd capturing group ) )*? # repeat as few times as needed X .*+\n # X on the first line and advance to next line ?+ # if 1st capturing group is defined, use it, consuming exactly the same number of characters as on the first line X .*+\n # X on the 2nd line and advance to next line ?+ # if 2st capturing group is defined, use it, consuming exactly the same number of characters as on the first line X # X on the 3rd line
此表達式利用具有自引用捕獲組的前瞻來計算X 出現之前每行上的字元數。如果偵測到該模式,則表達式將會匹配成功。
而使用正規表示式直接匹配無法提供由於lookbehind能力有限,無法準確計算垂直線形態,因此存在間接解決方案。
將以下表達式的所有符合項替換為$3,您可以獲得問題二的答案(興趣)作為結果字串的長度:
^ (?: (?: # match .+? characters . (?= # counting the same number on the following two lines .*+\n ( ?+ . ) .*+\n ( ?+ . ) ) )+? (?<= X ) # till the above consumes an X (?= # that matches the following conditions .*+\n ?+ (?<= X ) .*+\n ?+ (?<= X ) ) (?= # count the number of matches .*+\n ( ?+ . ) # the number of matches = length of ) )* # repeat as long as there are matches on this line .*\n? # remove the rest of the line
此表達式採用與第一個問題類似的技術,但進行了修改,將X 包含在第一個前瞻中匹配的字元中,並用量詞將其包裝起來來計算匹配的數量。
透過利用結果字串的長度作為計數,該解決方案提供了一種間接的方法來回答問題二。
以上是正規表示式可以用來計算 ASCII 影像中的垂直線結構嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!