Python Forum
trying to use/understand the "re"
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
trying to use/understand the "re"
#1
I'm trying to match only numbers in a string that has text also and I can't for the life of me figure out how the "re" module works with regular expressions. Below is what I have so far. I've been playing around with the regular expressions but just not getting it.

I want to only search for numbers only, not numbers with text. So "12" by itself, not "test12". Just the standalone numbers. Any help is greatly appreciated. Thank you!

import re

output = "12 test12 13 test13 14 test14 101 test101 102 test102"

num_input = int(input("\nEnter number to match: #: "))

num_string = str(num_input)

search = re.match(r'\^' + num_string '\$', output)

if num_string in search:
    print("yes")
else:
    print("no")
Reply
#2
You can play around with RegEx here.
And also refer to re documentation.

import re

output = "12 test12 13 test13 14 test14 101 test101 102 test102"

num_string = input("\nEnter number to match: #: ")

search = re.findall("[0-9]+", output)

if num_string in search:
    print("yes")
else:
    print("no")
Reply
#3
Awesome! Thank you! I did find the documentation but I was getting confused on some of it. And yesterday I was doing what you have but I was using other meta characters and getting myself confused with the white space notations.

This is great! And thanks for the link.
Reply
#4
(Mar-18-2019, 03:18 PM)gentoobob Wrote: I want to only search for numbers only, not numbers with text. So "12" by itself, not "test12". Just the standalone numbers. Any help is greatly appreciated. Thank you!
The need to Lookahead and Lookbehind as it called in regex,to make sure that numbers are alone and not in string.
>>> import re
>>> 
>>> output = "12 test12 13 test13 14 test14 101 test101 102 test102"
>>> r = re.findall(r"(?<!\S)\d+(?!\S)", output)
>>> r
['12', '13', '14', '101', '102']
Reply
#5
(Mar-18-2019, 05:03 PM)snippsat Wrote:
(Mar-18-2019, 03:18 PM)gentoobob Wrote: I want to only search for numbers only, not numbers with text. So "12" by itself, not "test12". Just the standalone numbers. Any help is greatly appreciated. Thank you!
The need to Lookahead and Lookbehind as it called in regex,to make sure that numbers are alone and not in string.
>>> import re
>>> 
>>> output = "12 test12 13 test13 14 test14 101 test101 102 test102"
>>> r = re.findall(r"(?<!\S)\d+(?!\S)", output)
>>> r
['12', '13', '14', '101', '102']


Thanks snippsat! I'd never gathered that combination of filtering on my own. That's what I was trying to do. I can at least learn from that and build on other things. Thank you again!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020