Change first occurance of a char and leave rest unchanged

A swapping-ground for Regular Expression syntax

Change first occurance of a char and leave rest unchanged

Postby Admin » Fri May 27, 2016 5:19 am

FAQ:
Is there any way of choosing a replacement only for the first occurrence of a character?
So, for example, change the first occurrence of underscore to dash and leave all other underscores unchanged...

ANSWER:
Yes, it is possible using RegEx (1). Use:

Match :
(.*?)(_)(.*)
Replace :
\1-\3

Note:
Adding a ? on a quantifier (?, * or +) makes it non-greedy.
So (.*) matches any characters (greedy)
So (.*?) matches any character (non-greedy=it stops at first match)
Admin
Site Admin
 
Posts: 1467
Joined: Tue Mar 08, 2005 8:39 pm

Return to Regular Expressions