简体   繁体   English

Python 字符串匹配的正则表达式

[英]Python Regular Expression for String Matching

Which regular expression can I use to match the strings of pattern- XX-YYY-XXXXXZ, where X is any digit, YYY is any alphabet pattern needed to be matched, Z is the alphabet.我可以使用哪个正则表达式来匹配模式字符串 - XX-YYY-XXXXXZ,其中 X 是任何数字,YYY 是需要匹配的任何字母模式,Z 是字母表。

for eg.例如。 if three strings are 89-ABC-98765Z, 76-GHI-67453H, 76-ABC-76453A I need the output strings with "ABC" ie 89-ABC-98765Z, 76-ABC-76453A如果三个字符串是 89-ABC-98765Z、76-GHI-67453H、76-ABC-76453A 我需要带有“ABC”的 output 字符串,即 89-ABC-98765Z、76-ABC-76453A

Trying to use str.match(r'.[0-9][ABC][0-9][AZ]?').尝试使用 str.match(r'.[0-9][ABC][0-9][AZ]?')。 PS I am trying to use it in a dataframe column. PS 我正在尝试在 dataframe 列中使用它。

import re

pattern = r'\d+-[A-Z]+-\d+[A-Z]'
text = 'for eg. if three strings are 89-ABC-98765Z, 76-GHI-67453H, 76-ABC-76453A I need the output strings with "ABC" i.e 89-ABC-98765Z, 76-ABC-76453A'
res = re.findall(pattern,text)
print(res)

The regex should be:正则表达式应该是:

\d{2}-ABC-\d{5}[A-Z]

Explanation:解释:

\d{2}   # 2 digits
-ABC-   # literal "-ABC-"
\d{5}   # 5 digits
[A-Z]   # any uppercase letter

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

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