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:

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

Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42

2 Answers2

6

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
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
  • 30,195
  • 12
  • 73
  • 107