简体   繁体   中英

How to extract specific pattern in Python

I am new to python
I want to extract specific pattern in python 3.5
pattern:
characters can be

how can I do this?

I have tried to use pattern [0-9\\*/+-xX\\0-9] but it returns either of the characters present in a string.

example: 2*3 or 2x3 or 2+3 or 2-3 should be matched
but asdXyz should not

You may use

[0-9][*+/xX-][0-9]

Or to match a whole string:

^[0-9][*+/xX-][0-9]$

In Python 3.x, you may discard the ^ (start of string anchor) and $ (end of string anchor) if you use the pattern in re.fullmatch ( demo ):

if re.fullmatch(r'[0-9][*+/xX-][0-9]', '5+5'):
    print('5+5 string found!')
if re.fullmatch(r'[0-9][*+/xX-][0-9]', '5+56'):
    print('5+56 string found!')
# => 5+5 string found!

The re.match() function will limit the search to the start and end of the string to prevent false positives.

  • A digit can be matched with \\d .
  • The operator can be matched with [x/+\\-] which matches exactly one of x , / , + , or - (which is escaped because it is a special regex character).
  • The last digit can be matched with \\d .
  • Putting parentheses around each part allows the parts to extracted as separate subgroups.

For example:

>>> re.match(r'(\d)([x/+\-])(\d)', '3/4').groups()
('3', '/', '4')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM