English 中文(简体)
如何将“以A开头或以B结尾”的模式与Python正则表达式相匹配?
原标题:How to match patterns "begins with A or ends with B" with Python regular expression?
  • 时间:2010-10-18 07:13:24
  •  标签:
  • python
  • regex
r (^|^A)(S+)(B$|$) 

结果匹配所有内容,实际上等于^S$。

如何写一个匹配“以A开头或以B结尾,可以两者都有,但不能两者都没有?”

PS:我还需要参考子串模块中的组(S+)。

示例:

匹配AanythinganythingB,并在替换中引用anything组。

最佳回答

问题已解决

我在python中使用这个正则表达式,我在python手册中发现了这一点:

(?(id/name)yes-pattern|no-pattern) Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn’t. no-pattern is optional and can be omitted. For example, (<)?(w+@w+(?:.w+)+)(?(1)>) is a poor email matching pattern, which will match with as well as user@host.com , but not with

2.4版中的新增功能。

所以我的最终答案是:

r (?P<prefix>A)?(?P<key>S+)(?(prefix)|B) 

命令:

>>>re.sub(r (?P<prefix>A)?(?P<key>S+)(?(prefix)|B) , g<key> ,"Aanything")

任何东西

>>>re.sub(r (?P<prefix>A)?(?P<key>S+)(?(prefix)|B) , g<key> ,"anythingB")

任何东西

虽然AanythingBanythingB还给我,但我无论如何都不在乎。

>>>re.sub(r (?P<prefix>A)?(?P<key>S+)(?(prefix)|B) , g<key> ,"AanythingB")

任何东西B

问题回答
(^A.*B$)|(^A.*$)|(^.*B$)

这是想要的行为吗?

var rx = /^((?:A)?)(.*?)((?:B)?)$/;
"Aanything".match(rx)
> ["Aanything", "A", "anything", ""]
"anythingB".match(rx)
> ["anythingB", "", "anything", "B"]
"AanythingB".match(rx)
> ["AanythingB", "A", "anything", "B"]
"anything".match(rx)
> ["anything", "", "anything", ""]
"AanythingB".replace(rx,  $1nothing$3 );
> "AnothingB"
"AanythingB".replace(rx,  $2 );
> "anything"

^A|B$^ A|.*B$(取决于匹配函数是否从一开始就匹配)

UPDATE

很难为此编写一个正则表达式。。

一种可能性是:

match = re.match(r ^(?:A(S+))|(?:(S+)B)$ , string)
if match:
    capture = max(match.groups())
# because match.groups() is either (capture, None) or (None, capture)

试试这个:

/(^A|B$)/

如果您不介意前缀“A”和后缀“B”都存在的情况下的额外权重,您可以使用较短的正则表达式:

reMatcher= re.compile(r"(?<=AA).*|.*(?=B)")

(对于^使用A,对于$则使用

当“A”和“B”都在各自的拐角处时,这个保持“A”前缀(而不是解决方案的“B”前缀):

 A text here  matches   text here 
 more text hereB  matches  more text here 
 AYES!B  matched  AYES! 
 neither  doesn t match

否则,非正则表达式的解决方案(有些人会说是更“Python”的解决方案)是:

def strip_prefix_suffix(text, prefix, suffix):
    left =  len(prefix) if text.startswith(prefix) else 0
    right= -len(suffix) if text.endswith(suffix) else None
    return text[left:right] if left or right else None

如果不匹配,函数将返回None,以区别于可能的(例如,当被调用为strip_refix_fsuffix(AB,a,B)时)。

PS我还应该说,这个正则表达式:

(?<=AA).*(?=B)|(?<=AA).*|.*(?=B)

应该工作,但没有;它的工作原理和我建议的一样,我不明白为什么。将正则表达式分解为多个部分,我们可以看到一些奇怪的东西:

>>> text=  AYES!B 
>>> re.compile( (?<=\AA).*(?=B\Z) ).search(text).group(0)
 YES! 
>>> re.compile( (?<=\AA).* ).search(text).group(0)
 YES!B 
>>> re.compile( .*(?=B\Z) ).search(text).group(0)
 AYES! 
>>> re.compile( (?<=\AA).*(?=B\Z)|(?<=\AA).* ).search(text).group(0)
 YES! 
>>> re.compile( (?<=\AA).*(?=B\Z)|.*(?=B\Z) ).search(text).group(0)
 AYES! 
>>> re.compile( (?<=\AA).*|.*(?=B\Z) ).search(text).group(0)
 AYES! 
>>> re.compile( (?<=\AA).*(?=B\Z)|(?<=\AA).*|.*(?=B\Z) ).search(text).group(0)
 AYES! 

出于某种奇怪的原因,.*(?=B\Z)子表达式优先,尽管它是最后一个替代表达式。





相关问题
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 ]="...

热门标签