簡體   English   中英

有人可以幫我為以下示例獲取適當的 REGEX 格式嗎

[英]Can someone help me to get the appropriate REGEX format for the following example

我想知道是否有人可以幫助為此示例獲取適當的正則表達式格式

##-AA-## Name of a Project     Information: no

我正在嘗試re.compile(r'')顯示項目名稱的信息。

我怎么知道我已經試過了

re.compile(r'(\s+([a-zA-Z]+\s+)+)') 

但不起作用。 或者我怎樣才能擺脫 PROJECT 之后的字符串。

嘗試這個:

import re

text = "##-AA-## Name of a Project     Information: no"

pattern = re.compile(r'(##-AA-##)(?P<project_name>.*?)(Information:)')

p_name = pattern.search(text).group('project_name').strip()

解釋

模式中有 3 組(括號中的每組):

  • 第一組捕獲項目名稱之前的所有內容
  • 第二組捕獲項目名稱。 請注意,我已為該組命名,以便在下一步中輕松檢索它,使用?P<group_name>語法
  • 第三組捕獲項目名稱后的所有內容

然后,您可以使用此模式搜索文本,並使用其名稱pattern.search(text).group('project_name')僅提取中間組。

strip()用於刪除不需要的空格。

你得到:

print(project_name)

>>> 'Name of a Project'

暫無
暫無

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

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