Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Python re.sub() how to include and slice the match in the substitution?
Parent
Python re.sub() how to include and slice the match in the substitution?
I recently started learning regular expressions and I'm trying to use Python's re module, specifically the re.sub() function, to convert a subset of Markdown syntax to HTML whenever it appears in a string. However, I haven't been able to figure out how to slice the source string so that the Markdown syntax is removed.
For example, the string This is a *test* string. should get converted to This is a <i>test</i> string., but it keeps the asteriks like so: This is a <i>*test*</i> string.
This is my code (the regex checks for backslashes in case the syntax is escaped and is non-greedy in case of multiple matches):
testString = re.sub(r'(?<!\\)\*.*?\*(?!\\)', r'<i>\g<0></i>', testString)
I've tried splitting up the substitution and using string splicing like this r'<i>' + r'\g<0>'[1:-1] + r'</i>', but that just returns an italicized 'g'.
Post
To answer your immediate question, use a capture group.
re.sub(r'(?<!\\)\*(.*?)\*(?!\\)', r'<i>\g<1></i>', testString)
With that out of the way, text parsing for a language is probably best served by an existing library.
For instance, r'(?<!\\)\*(.*?)\*(?!\\)'
is probably meant to be r'(?<!\\)\*(.*?)(?!\\)\*',
but r'This is a *test\* string*' will still mess up what you think it should do.

0 comment threads