Nate the Noob
Nate the Noob

Reputation: 370

Regex - Replace the first comma and last comma from the csv list but leave the middle one

I'm new to regex... but here goes.

So, Let's say I have this data.

13579,24680,13579,24680
13579,24680,13579,24680
13579,24680,13579,24680
13579,24680,13579,24680

So what I want is for it to replace the first comma, and the last comma with nothing. So I just end up with:

 1357924680,1357924680
 1357924680,1357924680
 1357924680,1357924680
 1357924680,1357924680

After it goes through.

I was thinking of a pattern somewhere along ^([^,]+),

But as you can tell, this doesn't work. Any suggestions or should I rethink what I use to do this?

Upvotes: 0

Views: 644

Answers (5)

Kent
Kent

Reputation: 195039

kent$  echo "13579,24680,13579,24680
"|sed -r 's#(^[0-9]+),(.*?),([0-9]+)$#\1\2\3#'
1357924680,1357924680

Upvotes: 0

Jonas Elfström
Jonas Elfström

Reputation: 31428

Ruby example

"13579,24680,13579,24680".gsub(/(.*?),(.*),(.*?)/,'\1\2\3')
=> "1357924680,1357924680"

and another example without using regex because it's always worth a try

"%s%s,%s%s" % "13579,24680,13579,24680".split(',')
=> "1357924680,1357924680"

Upvotes: 1

ennuikiller
ennuikiller

Reputation: 46965

This works in perl:

$match =~ s/^(.*?),(.*),(.*?)$/$1$2$3/;

Upvotes: 2

stema
stema

Reputation: 92976

Try

^(\d+),(\d+),(\d+),(\d+)

replace with

$1$2,$3$4

See it here on Regexr

Dependent on the way you access your text, you need to use the multiline modifier.

Upvotes: 1

Tom Knapen
Tom Knapen

Reputation: 2277

Try something like this:

regex: ^([^,]+),([^,]+),([^,]+),([^,]+)$
options: multiline
replace $1$2,$3$4

Upvotes: 3

Related Questions