簡體   English   中英

匹配特殊字符之間的字符串

[英]Match string between special characters

我對正則表達式有些了解,但在很大程度上對它並不熟悉。 字符串將采用以下格式:

\n\n*text here, can be any spaces, etc. etc.*

我將得到的字符串將有兩個換行符,后跟一個星號,然后是文本,然后以另一個星號結束。

我想從返回的文本中排除開頭的\\n\\n 到目前為止,這是我想出的模式,並且似乎可行:

pattern = "(?<=\\n\\n)\*(.*)(\*)"

match = re.search(pattern, string)
if match:
    text = match.group()
    print (text)
else:
    print ("Nothing")

我想知道是否有更好的方法來匹配此模式,或者我處理它的方式是否可以。

謝謝。

您可以使用以下方法避免捕獲組並獲得整個匹配結果:

pattern = r'(?<=\n\n\*)[^*]*(?=\*)'

例:

import re
print re.findall(r'(?<=\n\n\*)[^*]*(?=\*)','\n\n*text here, can be any spaces, etc. etc.*')

如果要在結果中包含星號,則可以改用:

pattern = r'(?<=\n\n)\*[^*]*\*'

在這樣的情況下,如果分隔符始終是靜態的並且位於字符串的頭部/尾部,則正則表達式會顯得過大。

>>> s = "\n\n*text here, can be any spaces, etc. etc.*"
>>> def CheckString(s):
...     if s.startswith("\n\n*") and s.endswith("*"):
...         return s[3:-1]
...     else:
...         return "(nothing)"
>>> CheckString(s)
'text here, can be any spaces, etc. etc.'
>>> CheckString("no delimiters")
'(nothing)'

(根據需要調整切片索引-我尚不清楚是否要保留前導/后綴'*'字符。如果要保留它們,請將切片更改為

return s[2:]

暫無
暫無

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

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