Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression except first

Tags:

java

regex

Hi I have string that could be like this:

%a%%%%%bc%%%d%

I need to replace the first % and the last %, at the start and at the end of the string with "". Also i need to replace all the %+ except the first one for each sequence group of string.

Result should be like this:

a%bc%d

How can I do with regex ? I tried something like this:.*?%(\W+)% but it didn't work

Thanks.

like image 458
DanieleO Avatar asked Jun 13 '26 08:06

DanieleO


1 Answers

You may use

.replaceAll("^%|%$|(%)+", "$1")

See the regex demo

Details:

  • ^% - the % at the start of the string is matched
  • | - or
  • %$ - a % at the string end
  • | - or
  • (%)+ - a repeated capturing group that matches 1+ % symbols, but captures only one % at each iteration into Group 1, and later, the $1 backreference to this group replaces multiple % chars with 1 %.
like image 70
Wiktor Stribiżew Avatar answered Jun 16 '26 02:06

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!