regex只有在至少在

2024-10-03 11:23:35 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python:如何让regex继续,前提是至少匹配了一次正向前瞻。你知道吗

我试着匹配:

Clinton-Orfalea-Brittingham Fellowship Program

下面是我现在使用的代码:

dp2= r'[A-Z][a-z]+(?:-\w+|\s[A-Z][a-z]+)+'
print np.unique(re.findall(dp2, tt))

我在匹配这个词,但它也匹配了一堆其他无关的词。 我的想法是,我希望\s[A-Z][a-z]只在-\w+至少被命中一次(或者可能两次)时启动。如有任何想法,我将不胜感激。你知道吗

澄清一下:我的目标不是专门匹配这组单词,而是能够在一般情况下匹配专有名词-专有名词-(不定次数),然后匹配一个不带连字符的专有名词。你知道吗

例如。 名词名词

名词

名词名词

最新迭代:

dp5=r'(?:[A-Z][A-Z]+-?){2,3}(?:\s\w+{2,4}'


Tags: 代码renpprogramregexuniqueprint名词
1条回答
网友
1楼 · 发布于 2024-10-03 11:23:35

{m,n}符号可用于强制正则表达式仅在mn次之间存在上一个表达式时才匹配。可能是这样的

(?:[A-Z][a-z]+-?){2,3}\s\w+\s\w+ # matches 'Clinton-Orfalea-Brittingham Fellowship Program'

如果您是专门寻找"Clinton-Orfalea-Brittingham Fellowship Program",为什么要使用Regex来寻找它?只需使用word in string。如果您正在寻找这样的形式:Name-Name-Name Noun Noun,这应该是可行的,但是请注意Name-Name-Name-Name Noun Noun不会,也不会Name-Name-Name Noun Noun Noun(事实上,像"Alice-Bob-Catherine Program"这样的东西不仅会匹配它,而且会匹配它后面的任何单词!)你知道吗

# Explanation

RE = r"""(?:        # Begins the group so we can repeat it
        [A-Z][a-z]+ # Matches one cap letter then any number of lowercase
        -?          # Allows a hyphen at the end of the word w/o requiring it
    ){2,3}          # Ends the group and requires the group match 2 or 3 times in a row
    \s\w+           # Matches a space and the next word
    \s\w+           # Does so again
    # those last two lines could just as easily be (?:\s\w+){2}
"""
RE = re.compile(RE,re.verbose) # will compile the expression as written

如果你特别寻找连字符专有名词,然后是非连字符专有名词,我会这样做:

[A-Z][a-z]+-(?:[A-Z][a-z]+(?:-|\s))+

# Explanation

RE = r"""[A-Z][a-z]+-   # Cap letter+small letters ending with a hyphen
         (?:            # start a non-cap group so we can repeat it
             [A-Z][a-z]+# As before, but doesn't require a hyphen
             (?:
                 -|\s   # but if it doesn't have a hyphen, it MUST have a space
             )          # (this group is just to give precedence to the |
         )+             # can match multiple of these.
    """

相关问题 更多 >