简体   繁体   中英

Print between string and a number through multiple lines

I'm trying to print the number 0123 which is located between a line of string and a line of a number

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)    

My code prints the output like this ( "0" ) which is wrong,I want my output to be like this ( "0123" )

You can try this. test Code:\\s*(.*?)(?=\\s+1)

"*" matches 0 or more ,"+" mathes 1 or more

You could capture your value without using a positive lookahead by matching the newline and the whitespace characters after the group.

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

Regex demo

If 1 should be between a line of string and an line of number only, you might use:

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

You could go for

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

See a demo on regex101.com (mind the verbose and the multiline flag).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM