[Python-ideas] Give regex operations more sugar

Michel Desmoulin desmoulinmichel at gmail.com
Wed Jun 13 09:33:52 EDT 2018



Le 13/06/2018 à 13:06, Ken Hilton a écrit :
> Hi all,
> 
> Regexes are really useful in many places, and to me it's sad to see the
> builtin "re" module having to resort to requiring a source string as an
> argument. It would be much more elegant to simply do "s.search(pattern)"
> than "re.search(pattern, s)".
> I suggest building all regex operations into the str class itself, as
> well as a new syntax for regular expressions.
> 
> Thus a "findall" for any lowercase letter in a string would look like this:
> 
>     >>> "1a3c5e7g9i".findall(!%[a-z]%)
>     ['a', 'c', 'e', 'g', 'i']
> 
> A "findall" for any letter, case insensitive:
> 
>     >>> "1A3c5E7g9I".findall(!%[a-z]%i)
>     ['A', 'c', 'E', 'g', 'I']
> 
> A substitution of any letter for the string " WOOF WOOF ":
> 
>     >>> "1a3c5e7g9i".sub(!%[a-z]% WOOF WOOF %)
>     '1 WOOF WOOF 3 WOOF WOOF 5 WOOF WOOF 7 WOOF WOOF 9 WOOF WOOF '
> 
> A substitution of any letter, case insensitive, for the string "hovercraft":
> 
>     >>> "1A3c5E7g9I".sub(!%[a-z]%hovercraft%i)
>     '1hovercraft3hovercraft5hovercraft7hovercraft9hovercraft'
> 
>

I often wished for findall and sub to be string methods, so +1 on that.

But there is really no need for a literal. A string pattern is plenty.


More information about the Python-ideas mailing list