English 中文(简体)
审视雷克斯模式,将类似结果退回到我目前的职能中
原标题:Looking for Regex pattern to return similar results to my current function

I have some pascal-cased text that I m trying to split into separate tokens/words. For example, "Hello123AIIsCool" would become ["Hello", "123", "AI", "Is", "Cool"].

Some Conditions

  • "Words" will always start with an upper-cased letter. E.g., "Hello"
  • A contiguous sequence of numbers should be left together. E.g., "123" -> ["123"], not ["1", "2", "3"]
  • A contiguous sequence of upper-cased letters should be kept together except when the last letter is the start to a new word as defined in the first condition. E.g., "ABCat" -> ["AB", "Cat"], not ["ABC", "at"]
  • There is no guarantee that each condition will have a match in a string. E.g., "Hello", "HelloAI", "HelloAIIsCool" "Hello123", "123AI", "AIIsCool", and any other combination I haven t provided are potential candidates.

我曾尝试过两岸差异。 以下两项尝试与我所希望的相当接近,但并非完全一样。

Version 0

import re


def extract_v0(string: str) -> list[str]:
    word_pattern = r"[A-Z][a-z]*"
    num_pattern = r"d+"
    pattern = f"{word_pattern}|{num_pattern}"
    extracts: list[str] = re.findall(
        pattern=pattern, string=string
    )
    return extracts


string = "Hello123AIIsCool"
extract_v0(string)
[ Hello ,  123 ,  A ,  I ,  Is ,  Cool ]

Version 1

import re


def extract_v1(string: str) -> list[str]:
    word_pattern = r"[A-Z][a-z]+"
    num_pattern = r"d+"
    upper_pattern = r"[A-Z][^a-z]*"
    pattern = f"{word_pattern}|{num_pattern}|{upper_pattern}"
    extracts: list[str] = re.findall(
        pattern=pattern, string=string
    )
    return extracts


string = "Hello123AIIsCool"
extract_v1(string)
[ Hello ,  123 ,  AII ,  Cool ]

Best Option So Far

这使用一种 combination和 lo。 它是行之有效的,但这是最佳解决办法吗? 还是有一些可以做的ancy?

import re


def extract_v2(string: str) -> list[str]:
    word_pattern = r"[A-Z][a-z]+"
    num_pattern = r"d+"
    upper_pattern = r"[A-Z][A-Z]*"
    groups = []
    for pattern in [word_pattern, num_pattern, upper_pattern]:
        while string.strip():
            group = re.search(pattern=pattern, string=string)
            if group is not None:
                groups.append(group)
                string = string[:group.start()] + " " + string[group.end():]
            else:
                break
    
    ordered = sorted(groups, key=lambda g: g.start())
    return [grp.group() for grp in ordered]


string = "Hello123AIIsCool"
extract_v2(string)
[ Hello ,  123 ,  AI ,  Is ,  Cool ]
问题回答

依据:

import re


def extract_v1(string: str) -> list[str]:
    word_pattern = r"[A-Z][a-z]+"
    num_pattern = r"d+"
    upper_pattern = r"[A-Z]+(?![a-z])"  # Fixed
    pattern = f"{word_pattern}|{num_pattern}|{upper_pattern}"
    extracts: list[str] = re.findall(
        pattern=pattern, string=string
    )
    return extracts


string = "Hello123AIIsCool"
extract_v1(string)

结果:

[ Hello ,  123 ,  AI ,  Is ,  Cool ]

固定的<代码>upper_pattern将尽可能贴上上层的字母,如存在,将停在下级信函之前。

使用<代码>re.sub和split()

import re

def pascal_case_split(identifier):
    return re.sub( ([A-Z][a-z]+) , r  1 , re.sub( ([A-Z]+) , r  1 , re.sub( ([0-9]+) , r  1 , identifier))).split()

a = pascal_case_split("Hello123AIIsCool")
a
[ Hello ,  123 ,  AI ,  Is ,  Cool ]

参引

<代码>re.findall 你们的工作应该少得多。 <代码>re.X,允许在轨值上平息。

>>> re.findall(
...   r ([A-Z]{2,} (?![a-z]) | d+ | [A-Z] [a-z]*) , 
...    Hello12 3AIIsCool , 
...   re.X
... )
[ Hello ,  123 ,  AI ,  Is ,  Cool ]




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签