[英]Match similar string in regex
我想知道是否有可能匹配兩條或多條相似線之一。
要匹配的字符串:
Its a string
Its a string
Its a string
異常結果:
Its a string
我嘗試的所有內容都只是 select 每一行,因為它們絕對相似。
是否可以始終保持一條相似的線不匹配?
我不能 100% 確定這對你有用,但它可以滿足我認為你正在嘗試做的事情。
import re
p = re.compile(r'(^.+$)((.|\n|r)*)^\1$', re.MULTILINE)
result = p.search(string)
repeated_line = result.groups()[0].strip()
您需要指定 re.MULTILINE 以便它可以捕獲 ^$ 字符。
這是正則表達式的快速制動:
(^.+$) # Matches a full line and captures it into '\1'
((.|\n|\r)*) # Matches any number of characters/newlines
^\1$ # Matches the first capturing group ensuring that the second occurrence fills a line and has it's own line.
可能有更好的方法來做到這一點,但這是我想到的第一個專門使用正則表達式的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.