简体   繁体   English

在模式中匹配RegEx模式

[英]Match RegEx pattern within pattern

Folks, 伙计们,

I have to match the following pattern: 我必须匹配以下模式:

First letter must be N Second any letter except P Third have to be S or T and the Fourth any letter except P again. 第一个字母必须是N,第二个必须是P以外的任何字母,第三个必须是S或T,第四个必须是P以外的任何字母。

The string is only capital letters, no number, white spaces, etc. 该字符串仅是大写字母,没有数字,空格等。

So using python this is what I got so far: 因此,使用python到目前为止,我得到的是:

import re
strRegex = r"N[^P][ST][^P]"
objRegex = re.compile(strRegex)

print objRegex.findall('NNSTL')

This will print: NNST 这将打印:NNST

What I expect is: NNST and NSTL 我期望的是:NNST和NSTL

Thanks 谢谢

re.findall will only return non-overlapping matches re.findall将仅返回非重叠匹配

Try this: 尝试这个:

    >>> strRegex = r"N[^P][ST][^P]"
    >>> regex = compile(strRegex)
    >>> def newfind(regex,str,pos=0):
    ...    result=regex.search(str,pos)
    ...    if result is None: return []
    ...    else: return [result.group()]+newfind(regex,str,result.start()+1)
    ...
    >>>
    >>> newfind(regex,'NNSTL')
    ['NNST', 'NSTL']

Reference: https://mail.python.org/pipermail/tutor/2005-September/041126.html 参考: https : //mail.python.org/pipermail/tutor/2005-September/041126.html

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

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