Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k 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 Answer

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']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...