Search code examples
pythonpython-re

How to get all text between [CODE][/CODE]?


I have text with tags [CODE]something here[/CODE]. How can I take only part between this tags, using re module.


Solution

  • Using the re.findall function we can use a regular expression with a capture group which will return a list of all the matches.

    import re
    
    regex = r"\[CODE\](.+?)\[\/CODE\]"
    
    test_str = "[CODE]Noob[/CODE] Nb[CODE]something here[/CODE]"
    
    matches = re.findall(regex, test_str)
    for match in matches:
        print(match)