How to extract the substring between two markers?

前端 未结 18 2590
慢半拍i
慢半拍i 2020-11-22 06:02

Let\'s say I have a string \'gfgfdAAA1234ZZZuijjk\' and I want to extract just the \'1234\' part.

I only know what will be the few characte

18条回答
  •  悲哀的现实
    2020-11-22 06:31

    Just in case somebody will have to do the same thing that I did. I had to extract everything inside parenthesis in a line. For example, if I have a line like 'US president (Barack Obama) met with ...' and I want to get only 'Barack Obama' this is solution:

    regex = '.*\((.*?)\).*'
    matches = re.search(regex, line)
    line = matches.group(1) + '\n'
    

    I.e. you need to block parenthesis with slash \ sign. Though it is a problem about more regular expressions that Python.

    Also, in some cases you may see 'r' symbols before regex definition. If there is no r prefix, you need to use escape characters like in C. Here is more discussion on that.

提交回复
热议问题