Click here to Skip to main content
16,017,922 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I would like to write a regex to replace/remove all repetitions of the first character in a string. An example: starting from the following string:
lorem ipsum dolor sit amet, consectetur adipisci elit, sed do eiusmod tempor incidunt ut labore et dolore magna aliqua

I would like to have the following:
orem ipsum door sit amet, consectetur adipisci eit, sed do eiusmod tempor incidunt ut abore et doore magna aiqua

where all the «l» are removed (replaced).

What I have tried:

Trying this:
(?=^(.))\1

Only the first character will be removed.

Trying this:
(?=(.))\1

All characters will be removed

Trying this:
(?=^(.))(.*)\1        Replace with $2

Only the last «l» will be removed.

What should I write?

Thank you
Posted

1 solution

Found!

(?<=^(.).*)(\1)

This string finds all characters that, after any sequence, are identical to the first. The first is excluded, but removing the first character is trivial.
 
Share this answer
 
Comments
0x01AA 16-Sep-24 11:29am    
Just out of curiosity: I'm assuming you are practice regular expressions? This because I see no other reason to use regular expressions for something like this?
Menci Lucio 16-Sep-24 12:43pm    
I realized a customization to filter some customer data for a complex app. That filters are a lot, have to be very flexible, and I'd like to customize them without regen the application. I created UI forms that are visible only by administrator. In this way, if there is the necessity to add, change, duplicate and modify something, it could be done directly changing the informations inside that UI. I put regex inside thoose UI forms to extract parts of data, to do checks, adjust length, and so on.

Yes, I have been practicing regex for about 30 years. I was a kid when I discovered them.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900