Reputation: 105
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
(?<=-).*(?=-)
Upvotes: 2
Views: 1786
Reputation: 18621
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
Upvotes: 1
Reputation: 163447
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]+(?=-)
Upvotes: 2
Reputation: 133600
With your shown samples please try following regex.
^-+([^-]*)-+$
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.
Upvotes: 1