0

I have string

MATERIAL :    51670 TUD1 =  .1200  m    TLD1 =  .0750  m TUD2 =  .0620  m    TLD2 =  .0380  m TUDH =  .0680  m    TLDH = .0420  m

I only want to extract [51670, .1200, .0750, .0620, .0380, .0680, .0420]

I have tried re.findall("[-+]?\d*\.\d+|\d+", lines) but it returns [' 51670', '1', '.1200', '1', '.0750', '2', '.0620', '2', '.0380', '.0680', '.0420'] which is not what I want. Please help.

0

2 Answers 2

1

You may use

(?<!\w)[-+]?\d*\.?\d+(?!\d)

See the regex demo

Here, the pattern matches

  • (?<!\w) - a location in the string that is not immediately preceded with a word char (letter, digit or _). To allow _, replace (?<!\w) with (?<![^\W_])
  • [-+]? - an optional - or +
  • \d*\.?\d+ - 0+ digits, an optinal dot and 1+ digits
  • (?!\d) - no digit allowed immediately to the right of the current location.

See Python demo:

import re
text = "MATERIAL :    51670 TUD1 =  .1200  m    TLD1 =  .0750  m TUD2 =  .0620  m    TLD2 =  .0380  m TUDH =  .0680  m    TLDH = .0420  m"
print( re.findall(r'(?<!\w)[-+]?\d*\.?\d+(?!\d)', text) )
# => ['51670', '.1200', '.0750', '.0620', '.0380', '.0680', '.0420']
Sign up to request clarification or add additional context in comments.

Comments

1

I would do:

import re
lines = 'MATERIAL :    51670 TUD1 =  .1200  m    TLD1 =  .0750  m TUD2 =  .0620  m    TLD2 =  .0380  m TUDH =  .0680  m    TLDH = .0420  m'
numbers = re.findall(r"\s(\.?\d+)\s",lines)
print(numbers)

Output:

['51670', '.1200', '.0750', '.0620', '.0380', '.0680', '.0420']

I simply look for 0 or 1 . (\.?) followed by 1 or more digits (\d+), which are between whitespaces (\s). I put \ses outside group so they will not appear in numbers. Note that above code will find all numbers from your example, but not numbers like 12.34 - to find them too use r"\s(\d+\.?\d+)\s". Note that . needs to be escaped as character with special meaning.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.