Is there a single regular expression to replace a number in a delimited list?
I have a string that can range from the empty string to an arbitrary list of comma delimited numbers. For example: "1,2,3"
Unfortunately as I wr开发者_开发技巧ite the code to remove an element I have a bunch of if statements--mainly to deal if it is the first, last, or only element in the list. I keep thinking there has got to be a better way!
For example, I would need to be able to remove the element '2
' in the following lists:
"1,2,3"
"1,3,2"
"2,1,3"
"2"
"12,2,21"
""
This should do what you want:
/(\b|,)2(\b|,)/
Removing (see below for replacing)
I couldn't find a simple single expression to remove, so it seems the best thing is just to match each of the patterns in sequence:
echo "x,x,1,x,2,x,x" | sed -e 's/,x,/,/g; s/^x,//; s/,x$//; s/^x$//'
A little verbose, but very readable.
Replacing
echo "x,x,1,x,2,x,x" | sed -e 's/,x,/,y,/g; s/^x,/y,/; s/,x$/,y/; s/^x$/y/'
精彩评论