代码之家  ›  专栏  ›  技术社区  ›  iamabhaykmr

Python在使用boundary[duplicate]时没有基于regex提取匹配的文本

  •  1
  • iamabhaykmr  · 技术社区  · 7 年前

    我正在提取 this text from regex ,我匹配了文本中所需的字符串,但在使用python re提取那些匹配的文本时,它没有提取。

    这是我正在使用的代码。

    import re
    PRICE = '\b(price|rs)?\s*(\d+[\s\d.]*\s*?(pkg|k|m| 
    (?:la(?:c|kh|k)|crore|cr)s?|l)\b\.?)'
    
    content ='This should matchprice  5.6 lacincluding price(i.e  price 
    5.6 lac) and rs 56 m. including rs (i.e rs 56 k  rs 56 m) .
    
    It will match normally if there is no price or rs written for example 
    or   56 k or 8.8 crs. are correct matching.
    
    It should not match5.6  lac (Should not match eitherrs 6 lac asas 
    there is no spaces before 5.6'
    
    for m in re.finditer(PRICE,content,pat.FLAG):
        matched = m.group().strip()
        print ("In matched "+ matched)`
    

    上面的代码没有进入for循环。非常感谢任何线索。谢谢。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Giacomo Alzetta    7 年前

    使用原始字符串定义正则表达式:

    PRICE = r'\b(price|rs)?\s*(\d+[\s\d.]*\s*?(pkg|k|m|(?:la(?:c|kh|k)|crore|cr)s?|l)\b\.?)'
    

    否则 \b 解释为退格:

    >>> print '\b(price|rs)?\s*(\d+[\s\d.]*\s*?(pkg|k|m|(?:la(?:c|kh|k)|crore|cr)s?|l)\b\.?)'
    (price|rs)?\s*(\d+[\s\d.]*\s*?(pkg|k|m|(?:la(?:c|kh|k)|crore|cr)s?|l\.?)
    >>> print r'\b(price|rs)?\s*(\d+[\s\d.]*\s*?(pkg|k|m|(?:la(?:c|kh|k)|crore|cr)s?|l)\b\.?)'
    \b(price|rs)?\s*(\d+[\s\d.]*\s*?(pkg|k|m|(?:la(?:c|kh|k)|crore|cr)s?|l)\b\.?)
    

    注意第一个 print 输出不包含初始 . 请记住,字符串首先由python编译器解释,这意味着 \n 换行或 退格或 \x42 B re 解释自身转义的模块。因此,在99.9%的情况下,您希望避免编译器解释转义。原始字符串就是这样做的。