簡體   English   中英

通過多行在字符串和數字之間打印

[英]Print between string and a number through multiple lines

我正在嘗試打印位於字符串行和數字行之間的數字0123

import re

s = """
test Code:
0123

1

text1 text2

   """

if re.findall(r'test Code:\s*(.*?)(?=\s*1)', s):

 test=re.findall(r'test Code:\s*(.*?)(?=\s*1)', s)

 print(test)    

我的代碼打印出這樣的輸出( "0" ) ,這是錯誤的,我希望我的輸出像這樣( "0123" )

你可以試試看 test Code:\\s*(.*?)(?=\\s+1)

“ *”匹配0或更多,“ +”匹配1或更多

您可以通過在組后匹配換行符和空格字符來捕獲您的價值,而無需使用積極的前瞻性。

test Code:\n\s*(\d+)\s*\n\s*1

正則表達式演示

如果1僅應在字符串行和數字行之間,則可以使用:

^test Code:\n\s*(\d+)\s*\n\s*1\s*$

你可以去

^
[^\d\n]+[\r\n] # line without digits
(\d+)[\r\n]    # only digits in that line
\s+\d+         # whitespaces + digits

請參閱regex101.com上的演示 (注意詳細信息和多行標志)。

暫無
暫無

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

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