A regular expression that matches a number in an python string

  • 2021-07-09 08:33:40
  • OfStack

Introduction to Python Regular Expressions

A regular expression is a special sequence of characters that makes it easy to check whether a string matches a pattern.

Python has added re module since version 1.5, which provides Perl-style regular expression mode.

The re module enables the Python language to have all the regular expression functionality.

The compile function generates a regular expression object based on a pattern string and optional flag arguments. This object has 1 series of methods for regular expression matching and replacement.

The re module also provides functions that are identical to the functionality of these methods, using a pattern string as their first argument.

This section introduces you to python regular expression 03-matching numbers in strings


import re
# \d+  Matches the numeric part of a string and returns a list 
ss = 'adafasw12314egrdf5236qew'
num = re.findall('\d+',ss)
print(num)
# Running result 
#['12314', '5236']

\ d + Use matching numbers

ps: The following python regular expressions find pure numbers in strings

1. Simple practice


>>> import re
>>> re.findall(r'\d+', 'hello 42 I'm a 32 string 30')
['42', '32', '30']

However, this makes it possible to recognize non-pure digits in a string


>>> re.findall(r'\d+', "hello 42 I'm a 32 str12312ing 30")
['42', '32', '12312', '30']

2. Identify pure numbers

If you only need numbers separated by word boundaries (spaces, periods, commas), you can use\ b


>>> re.findall(r'\b\d+\b', "hello 42 I'm a 32 str12312ing 30")
['42', '32', '30']
>>> re.findall(r'\b\d+\b', "hello,42 I'm a 32 str12312ing 30")
['42', '32', '30']
>>> re.findall(r'\b\d+\b', "hello,42 I'm a 32 str 12312ing 30")
['42', '32', '30']

Summarize


Related articles: