首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >寻找合适的RE

寻找合适的RE
EN

Stack Overflow用户
提问于 2013-02-12 03:35:37
回答 1查看 95关注 0票数 1

刚开始使用正则表达式...我正在寻找一个正则表达式

类似于\b\d\d\b,但数字可能不同。(例如,23应匹配

但22不应该)我已经尝试了很多(涉及反向引用),但它们都失败了。

我已经用下面的代码( python 2.7.3)尝试了RE,但到目前为止还没有匹配到的代码

代码语言:javascript
复制
import re
# accept a raw string(e) as input
# and return a function with an argument
# 'string' which returns a re.Match object
# on succes. Else it returns None
def myMatch(e):
    RegexObj= re.compile(e)
    return RegexObj.match

menu= raw_input
expr= "expression\n:>"
Quit= 'q'
NewExpression= 'r'
str2match= "string to match\n:>"
validate= myMatch(menu(expr))
# exits when the user # hits 'q'
while True:                     
    # set the string to match or hit 'q' or 'r'
    option = menu(str2match)
    if option== Quit: break 
    #invokes when the user hits 'r'
    #setting the new expression
    elif option== NewExpression:
        validate= myMatch(menu(expr))
        continue
    reMatchObject= validate(option) 
    # we have a match ! 
    if reMatchObject:           
        print "Pattern: ",reMatchObject.re.pattern
        print "group(0): ",reMatchObject.group()
        print "groups: ",reMatchObject.groups()
    else:
        print "No match found "
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-12 03:37:02

您可以使用反向引用和负向前视。

代码语言:javascript
复制
\b(\d)(?!\1)\d\b

反向引用被替换为第一个组中匹配的任何内容:(\d)

如果以下字符与表达式匹配,则否定的先行查找会阻止匹配成功。

所以这基本上是说匹配一个数字(我们称之为"N")。如果下一个字符是N,则匹配失败。如果不匹配,则再匹配一个数字。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14819514

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档