Search code examples
pythonregexregex-negationregex-group

How do I use a regular expression to put the beginning of a string, preceding some user-specified character, into a group?


This question was asked here, but I do not want a python specific solution. It should work in JavaScript, and any other mainstream language. It must be a regular expression.

Suppose that the delimiter was "!"

The table below shows the desired behavior for a few sample inputs

+------------------------+--------+
|         INPUT          | OUTPUT |
+------------------------+--------+
| "aaaa!bbbb"            | "aaaa" |
| "aaaa"                 | "aaaa" |
| "aaaa!bbbb!ccccc!dddd" | "aaaa" |
| "aaaa!"                | "aaaa" |
| "!aaaaa"               | ""     |
+------------------------+--------+    

I tried the following to no avail:

"^[^!]*$(!)"


Solution

  • You don't need (!) at the end. Just use ^([^!]*).