Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression all characters except last one

Tags:

regex

This is my string: 50.00.00..00.00

I want to match all . except the last one, so after a replace I end up with 50000000.00

Can somebody help me with this?

like image 286
malamili Avatar asked Dec 29 '11 13:12

malamili


People also ask

How do you match a character except one?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '. ' (period) is a metacharacter (it sometimes has a special meaning).

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


2 Answers

\.(?=.*\.)

Matches a dot (\.), which there must be another dot following it ((?=.*\.)).

(This assumes the regex engine supports lookahead, e.g. PCRE, Python, etc.)

like image 168
kennytm Avatar answered Sep 24 '22 09:09

kennytm


So you did not specified your regex tools, engine, etc. Well you can do this with e.g. sed (only work if there are always two digits after the last dot and the last dot is always present):

echo "50.00.00..00.00" | sed 's/\.//;s/\(..\)$/.\1/'

But there are several other ways, e.g. with lookahead regex (if it's supported for you).

HTH

like image 23
Zsolt Botykai Avatar answered Sep 25 '22 09:09

Zsolt Botykai