C.A
C.A

Reputation: 620

Is it possible to regex replace at first occurence AND last occurence of a char?

I am trying to replace | with "" at first and last occurrence.

Example:

"Hello | my name | is | Jason | and I like hacking"

So far I can only do one or the other.

First occurrence:

^(.*?)[|]

Last occurrence:

(|)[^|]*$"

Is it possible to replace both at once or do you have to do it in steps?

Upvotes: 3

Views: 4551

Answers (4)

Luke
Luke

Reputation: 156

Some other answers should work, but I believe they may be slightly overengineered. The simple regex below should work.

\|(.*)\|

Demo

This regex works because .* is greedy, giving back as needed for the pattern to match. In this case, that means the capture group will capture everything between the first and last pipe. You can then replace the pipes with whatever characters you need. Javascript example below.

var str = "Hello | my name | is | Jason | and I like hacking";
var regex = /\|(.*)\|/;
str = str.replace(regex, "\"$1\"");

Upvotes: 0

MRAB
MRAB

Reputation: 20664

Think of the string as consisting of these parts: the part before the first pipe, a pipe, the middle part, a pipe, and the part after the last pipe.

Capture the parts you want: ([^|]*)[|](.*)[|](.*)

and then build the result from those captured parts: $1$2$3

Upvotes: 1

stema
stema

Reputation: 92996

Try this

^([^|]*)\||\|(?=[^|]*$)

and replace it with

$1"

See it here on Regexr

The trick here is to match the first part in the string with the capturing group and write it in the replacement string. For the second alternative that matches the last "|" there is no capturing group so this will be filled with the empty string and does not hurt in the replacement string.

Upvotes: 3

davidrac
davidrac

Reputation: 10738

I think this can do the trick: (?:^[^|]*(\|))|(?:(\|)[^|]*$)

You'll get the first and last | in the match groups

If you use a RegEx engine that supports variable length lookbehind I think this will work: (?<=^[^|]*)\||\|(?=[^|]*$)

You'll match only the first and last |

Upvotes: 1

Related Questions