Python: preg_replace function analog

Roman Nazarkin picture Roman Nazarkin · Mar 11, 2013 · Viewed 9.2k times · Source

I have a litle expression in PHP:

  $search = array("'<(script|noscript|style|noindex)[^>]*?>.*?</(script|noscript|style|noindex)>'si",
    "'<\!--.*?-->'si",
    "'<[\/\!]*?[^<>]*?>'si",
    "'([\r\n])[\s]+'");

$replace = array ("",
  "",
  " ", 
  "\\1 ");

  $text = preg_replace($search, $replace, $this->pageHtml);

How i did run this on python? re.sub?

Answer

icc97 picture icc97 · Jan 24, 2016

As @bereal commented use the Regular Expression module re.sub.

Here's a simple example

Python:

>>> import re
>>> re.sub(r'([^A-Z])([A-Z])', r'\1_\2', 'camelCase').lower()
'camel_case'

And just for kicks here's it on PHP too:

<?php
echo strtolower(preg_replace('/([^A-Z])([A-Z])/', '$1_$2', 'camelCase'));
// prints camel_case