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

正则表达式:匹配开始或空格

  •  42
  • Mat  · 技术社区  · 17 年前

    正则表达式可以匹配空格吗 字符串的开头?

    我想用一个符号来代替货币缩写GBP。我可以从英镑开始匹配任何东西,但我想更保守一点,并在它周围寻找某些分隔符。

    >>> import re
    >>> text = u'GBP 5 Off when you spend GBP75.00'
    
    >>> re.sub(ur'GBP([\W\d])', ur'£\g<1>', text) # matches GBP with any prefix
    u'\xa3 5 Off when you spend \xa375.00'
    
    >>> re.sub(ur'^GBP([\W\d])', ur'£\g<1>', text) # matches at start only
    u'\xa3 5 Off when you spend GBP75.00'
    
    >>> re.sub(ur'(\W)GBP([\W\d])', ur'\g<1>£\g<2>', text) # matches whitespace prefix only
    u'GBP 5 Off when you spend \xa375.00'
    

    7 回复  |  直到 17 年前
        1
  •  75
  •   Zach Scrivena    17 年前

    使用“或” | “运营商:

    >>> re.sub(r'(^|\W)GBP([\W\d])', u'\g<1>£\g<2>', text)
    u'\xa3 5 Off when you spend \xa375.00'
    
        2
  •  60
  •   Motti    10 年前

    \b 是单词边界,可以是空白、行的开头或非字母数字符号( \bGBP\b ).

        3
  •  6
  •   Peter Mortensen Pieter Jan Bonestroo    15 年前

    word boundary (字符串的开头已经是),GBP之后是一个数值或字边界:

    re.sub(u'\bGBP(?=\b|\d)', u'£', text)
    

    lookahead . 是否足够包容?

        4
  •  4
  •   Wiktor Stribiżew    7 年前

    左侧空白边界(字符串中的一个位置,它要么是字符串开头,要么在空白字符后面)可以用

    (?<!\S)   # A negative lookbehind requiring no non-whitespace char immediately to the left of the current position
    (?<=\s|^) # A positive lookbehind requiring a whitespace or start of string immediately to the left of the current position
    (?:\s|^)  # A non-capturing group matching either a whitespace or start of string 
    (\s|^)    # A capturing group matching either a whitespace or start of string
    

    见 regex demo . Python 3 demo :

    import re
    rx = r'(?<!\S)GBP([\W\d])'
    text = 'GBP 5 Off when you spend GBP75.00'
    print( re.sub(rx, r'£\1', text) )
    # => £ 5 Off when you spend £75.00
    

    注意:您可以使用 \1 \g<1> 在替换模式中,因为当后面没有数字时,不需要明确的反向引用。

    (?!\S)   # A negative lookahead requiring no non-whitespace char immediately to the right of the current position
    (?=\s|$) # A positive lookahead requiring a whitespace or end of string immediately to the right of the current position
    (?:\s|$)  # A non-capturing group matching either a whitespace or end of string 
    (\s|$)    # A capturing group matching either a whitespace or end of string
    
        5
  •  2
  •   Christoph    17 年前

    我想你在找我 '(^|\W)GBP([\W\d])'

        6
  •  0
  •   duffymo    17 年前

        7
  •  0
  •   Svante    17 年前

    是的,为什么不呢?

    re.sub(u'^\W*GBP...
    

    匹配字符串的开头,0个或更多空格,然后是GBP。。。

    :哦,我想你需要替换,用 | :

    re.sub(u'(^|\W)GBP...
    
        8
  •  0
  •   joel.neely    17 年前

    它在Perl中工作:

    $text = 'GBP 5 off when you spend GBP75';
    $text =~ s/(\W|^)GBP([\W\d])/$1\$$2/g;
    printf "$text\n";
    

    $ 5 off when you spend $75
    

    请注意,我规定匹配应该是全局的,以获得所有的匹配。