1

Given a string:

#symbol 1# / 7 - #symbol 2#

I want to return:

func('#symbol 1#') / 7 - func('#symbol 2#')

I've tried:

re.sub('[#*#]', 'func(\'', f2)

which gives:

func(symbol 1func( / 7 - func(symbol 2func(

where I don't want the func(' for the second hash.

Is there a way to get the end of the hash replaced with ') using the re.sub?

1 Answer 1

3

You may use a regex like

#[^\s#](?:[^#]*[^\s#])?#

Replace with func('\g<0>') where \g<0> refers to the whole match. See the regex demo.

Details

  • # - a # char
  • [^\s#] - a char other than whitespace and #
  • (?:[^#]*[^\s#])? - an optional non-capturing group matching 1 or 0 occurrences of
    • [^#]* - 0 or more chars other than #
    • [^\s#] - a char other than whitespace and #
  • # - a # char.

See the Python demo:

import re
text = '#symbol 1# / 7 - #symbol 2#'
print( re.sub(r'#[^\s#](?:[^#]*[^\s#])?#', r"func('\g<0>')", text) )
# => func('#symbol 1#') / 7 - func('#symbol 2#')
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Thanks for that. As a slight amendment how could I change this to handle spaces in the symbols: '#symbol 1 like this# / 7 - #symbol 2 like that#'
@JDoe #[\w\s]+# or #[^#]+# or #[^\s#](?:[^#]*[^\s#])?#. It depends on what the rule for what can be in between the delimiting #s. Please add the requirement to the question, I will fix the regex accordingly.
Thank you - that saved me a lot of time!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.