Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

python - Regex pattern to get only the 3-digit numerical value when there is ddd in a line

I'm trying to get only the 3 digit numerical values if there is ddd in a line, Here is my input string:

here we can also have 370
Hey I have 324 as best value today for 21ddd.

In the above string i want to get the 3 digit numerical value if there is ddd in a line, which means i want to get only the 324 as my output.

bellow is the pattern which I tried:

price_1 = re.findall(r's*d{3}(?!s*d{2}DDD)', line)

output:

[' 370', ' 324']

But the output I need is:

['324']

can any one tell me the right pattern to get the exact output?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the ddd can be before of after the 3 digits:

^(?=.*ddd).*(d{3})

Explanation

  • ^ Start of string
  • (?=.*ddd) positive lookahead to assert ddd
  • .*(d{3}) Match 3 digits in capture group 1

Regex demo

For example

import re

regex = r"^(?=.*ddd).*(d{3})"
s = ("here we can also have 370
"
    "Hey I have 324 as best value today for 21ddd.")
print(re.findall(regex, s, re.MULTILINE | re.IGNORECASE))

Output

['324']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...