0

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:

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

Samuel Muldoon
  • 1,224
  • 3
  • 17

2 Answers2

6

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

Barmar
  • 669,327
  • 51
  • 454
  • 560
0

You can use a capturing group for the part up to (but not including) ! and replace the match with the first group:

^([^!]+)($|!.*$)

Regex 101 demo

Frank Schmitt
  • 28,996
  • 10
  • 68
  • 104