简体   繁体   English

如何在Python中提取特定模式

[英]How to extract specific pattern in Python

I am new to python 我是python的新手
I want to extract specific pattern in python 3.5 我想在python 3.5中提取特定的模式
pattern: digit character digit pattern: 数字字符数字
characters can be * + - / x X 字符可以是* + - / x X.

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. 我试图使用模式[0-9 \\ * / + - xX \\ 0-9],但它返回字符串中的任何一个字符。

example: 2*3 or 2x3 or 2+3 or 2-3 should be matched 例如:应匹配2 * 3或2x3或2 + 3或2-3
but asdXyz should not 但asdXyz不应该

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 ): 在Python 3.x中,如果在re.fullmatchdemo )中使用模式,则可以丢弃^ (字符串锚点的开头)和$ (字符串锚点的结尾):

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. re.match()函数将搜索限制在字符串的开头和结尾以防止误报。

  • A digit can be matched with \\d . 数字可以与\\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). 运算符可以与[x/+\\-]匹配,它只匹配x/+- (由于它是一个特殊的正则表达式字符,因此被转义)。
  • The last digit can be matched with \\d . 最后一位数字可与\\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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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