SORU
29 Ocak 2009, PERŞEMBE


(Python) - daha basit bir yol yerine düzenli ifade?

Metin daha büyük bir parça bir parçası olan bir parça metin değiştirmek istediğim zaman, ben her zaman yapacak bir iş vardır:

"(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)"

Sonra replace end grup için yeni veri ile start grubuna bağlamak.

Bunun için daha iyi bir yöntem var mı?

CEVAP
29 Ocak 2009, PERŞEMBE


>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(. )(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a callable, it's passed the match object and must return
    a replacement string to be used.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Booredatwork.com

    Booredatwork

    5 Ocak 2009
  • Kontor.TV

    Kontor.TV

    14 Mart 2006
  • kruno j

    kruno j

    6 Mayıs 2007