Replace underscore from all html href with regex and python

Viewed 51

So I'm currently using python.

How can I go through a HTML file and replace all occurrences of:

<a href="#some_snake_case_text">

and transform it into:

<a href="#somesnakecasetext">

independent of the text there is inside the the href?

So I was going for Regex, I'm now a couple of hours in and I didn't succeed in matching the "_" in-between the href tag in order to remove them... I cannot just match the word and do a replace all cus that would actually replace all those through the entire document which is not intended.

I tried this to math all the "_"

<a href=\"#(.*(_).*)+\">

or everything but the underscores:

<a href=\"#([^_]_?)+\">

to then maybe replace it?!

How can I do this?

2 Answers

You can use re.sub:

import re
s = '<a href="#some_snake_case_text">'
new_s = re.sub('(?<=href\=")[^"]+', lambda x:''.join(x.group().split('_')), s)

Output:

'<a href="#somesnakecasetext">'

With a method in replacement:

import re

def subst(x):
    return x.group().replace('_', '')

s = 'xxx <a href="#some_snake_case_text"> xxx'
p = r'<a\s+href="#[^"]*">'
print(re.sub(p, subst, s))

See Python proof.

Results: xxx <a href="#somesnakecasetext"> xxx

EXPLANATION

--------------------------------------------------------------------------------
  <a                       '<a'
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  href="#                  'href="#'
--------------------------------------------------------------------------------
  [^"]*                    any character except: '"' (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  ">                       '">'
Related