簡體   English   中英

匹配任意分割多行的字符串

[英]Matching a string that's arbitrarily splits over multiple lines

在正則表達式中是否有一種方法可以匹配任意分割為多行的字符串 - 比如我們在文件中有以下格式:

msgid "This is "
"an example string"
msgstr "..."

msgid "This is an example string"
msgstr "..."

msgid ""
"This is an " 
"example" 
" string"
msgstr "..."

msgid "This is " 
"an unmatching string" 
msgstr "..."

因此,我們希望有一個匹配所有示例字符串的模式,即:匹配字符串,無論它是如何跨行分割的。 請注意,我們在示例中顯示的特定字符串之后,而不僅僅是任何字符串。 所以在這種情況下,我們希望匹配字符串"This is an example string"

當然我們可以輕松地連接字符串然后應用匹配,但讓我想知道這是否可能。 我正在談論Python正則表達式,但一般的答案是可以的。

你想要匹配一系列單詞嗎? 如果是這樣,你可以查找中間只有空格(\\ s)的單詞,因為\\ s匹配換行符和空格。

import re

search_for = "This is an example string"
search_for_re = r"\b" + r"\s+".join(search_for.split()) + r"\b"
pattern = re.compile(search_for_re)
match = lambda s: pattern.match(s) is not None

s = "This is an example string"
print match(s), ":", repr(s)

s = "This is an \n example string"
print match(s), ":", repr(s)

s = "This is \n an unmatching string"
print match(s), ":", repr(s)

打印:

True : 'This is an example string'
True : 'This is an \n example string'
False : 'This is \n an unmatching string'

由於需要在每一行上引用,以及空行的容差,這有點棘手。 這是一個與您正確發布的文件匹配的正則表達式:

'(""\n)*"This(( "\n(""\n)*")|("\n(""\n)*" )| )is(( "\n(""\n)*")|("\n(""\n)*" )| )an(( "\n(""\n)*")|("\n(""\n)*" )| )example(( "\n(""\n)*")|("\n(""\n)*" )| )string"'

這有點令人困惑,但它只是你要匹配的字符串,但它始於:

(""\n)*"

並用以下內容替換每個單詞之間的空格:

(( "\n(""\n)*")|("\n(""\n)*" )| )

它檢查每個單詞后面的三種不同的可能性,“空格,引號,換行符,(無限數量的空字符串)引用”,或者相同的序列,但更多的空間到最后,或只是一個空格。

一個更容易實現這個工作的方法是編寫一個小函數,它將接收你想要匹配的字符串並返回與之匹配的正則表達式:

def getregex(string):
    return '(""\n)*"' + string.replace(" ", '(( "\n(""\n)*")|("\n(""\n)*" )| )') + '"'

所以,如果你有一個名為“filestring”的字符串中的文件,你會得到這樣的匹配:

import re

def getregex(string):
    return '(""\n)*"' + string.replace(" ", '(( "\n(""\n)*")|("\n(""\n)*" )| )') + '"'

matcher = re.compile(getregex("This is an example string"))

for i in matcher.finditer(filestring):
    print i.group(0), "\n"

>>> "This is "
    "an example string"

    "This is an example string"

    ""
    "This is an "
    "example"
    " string"

這個正則表達式沒有考慮你在第三個msgid中的“示例”之后的空間,但我認為這是由機器生成的,這是一個錯誤。

暫無
暫無

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

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