Regular expression to extract text between multiple hyphens

Viewed 541

I have a string in the following format

----------some text-------------

How do I extract "some text" without the hyphens? I have tried with this but it matches the whole string

(?<=-).*(?=-)
3 Answers

The pattern matches the whole line except the first and last hyphen due to the assertions on the left and right and the . also matches a hyphen.

You can keep using the assertions, and match any char except a hyphen using [^-]+ which is a negated character class.

(?<=-)[^-]+(?=-)

See a regex demo.

Note: if you also want to prevent matching a newline you can use (?<=-)[^-\r\n]+(?=-)

With your shown samples please try following regex.

^-+([^-]*)-+$

Online regex demo

Explanation: Matching all dashes from starting 1 or more occurrences then creating one and only capturing group which has everything matched till next - comes, then matching all dashes till last of value.

You are using Python, right? Then you do not need regex.

Use

s = "----------some text-------------"
print(s.strip("-"))

Results: some text.

See Python proof.

With regex, the same can be achieved using

re.sub(r'^-+|-+$', '', s)

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  -+                       '-' (1 or more times (matching the most
                           amount possible))
--------------------------------------------------------------------------------
 |                        OR
--------------------------------------------------------------------------------
  -+                       '-' (1 or more times (matching the most
                           amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
Related