Tomas Storås
Tomas Storås

Reputation: 71

Adding to beginning of string with regex

So I'm trying to add two hashes to all strings that begin with a letter following a dot.

It should apply only if it is the beginning of the string. I'm new to regex, so I'm not sure how I should do the adding. Any help?

import re
string = "a. this is a sentence.bla bla."
string = re.sub(r"\A[a-h][.]","##", string)

The result is (obviously) "## this is a sentence.bla bla.".

How do I add to the string instead of replacing?

The result should be: "##a. this is a sentence.bla bla."

Upvotes: 1

Views: 1299

Answers (1)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Use

import re
s = "a. this is a sentence.bla bla."
s = re.sub(r"\A[a-h][.]",r"##\g<0>", s)

See Python proof.

"##\g<0> inserts ## before text matched (expressed with \g<0>).

Upvotes: 2

Related Questions