1
votes

I have a text file which has multiple strings between '-', and i'm trying to print every string that is between '-'

I have tried this code but, it's skipping values.

import re

text=   """
        -text1-text2-text3
        -text4-
        """

result = re.findall(r'-(.*?)-', text)
print(result,end="")

I'm trying to get the result to come up like this:

['text1','text2','text3'],'text4']

but instead my code is skipping values and giving me this:

['text1','text4']

2
Glad my answer worked for you. Please also consider upvoting if my answer proved helpful to you (see How to upvote on Stack Overflow?) as you are entitled to the upvoting privilege after reaching 15 rep points. Note you may upvote all the answers that turned out helpful. - Wiktor Stribiżew

2 Answers

0
votes

You may use

-\s*(.*?)(?=\s*-)

See the regex demo and the regex graph:

enter image description here

See the Python demo:

import re
text=   """
        -text1-text2-text3
        -text4-
        """
result = re.findall(r'-\s*(.*?)(?=\s*-)', text)
print(result) # => ['text1', 'text2', 'text3', 'text4']

If you need to match across lines, add the re.S or re.DOTALL flag to re.findall.

Regex details

  • - - a hyphen
  • \s* - 0+ whitespaces
  • (.*?) - Capturing group 1: any 0+ chars other than line break chars
  • (?=\s*-) - a positive lookahead that requires 0+ whitespaces and then - immediately to the right of the current location
0
votes

Try this simple regex r'(?<=-)[^-]*(?=-)'

>>> import re
>>> text=   """
...         -text1-text2-text3
...         -text4-
...         """
>>> print ([x.strip() for x in re.findall(r'(?<=-)[^-]*(?=-)', text)])
['text1', 'text2', 'text3', 'text4']