Skip to main content

Hello,

 

I am seeking help with using a Regex to replace the first instance of an underscore in a string.

 

I am using a BulkAttributeRenamer to rename a series of attributes with multiple underscores like this as an example: 0_4_C11_M

 

I am trying to replace just the first underscore in the string with a dash with a regex replace to change the name from 0_4_C11_M to 0-4_C11_M. The regex I’m using is ([\_]+)

 

When I test that expression in RegEx101 is does exactly what I need and only replaces the first underscore in the string as shown below:

However, when I use the same expression in the BulkAttributeRenamer it’s returning and replacing all underscores as shown below:

Hoping someone can help with advice on how to limit the return to just the first underscore in the string please - it the expression incorrect or is there something else I need to add to the parameters? Thanks :)

With replacements, I usually use a more explicit form in RegEx to avoid this.  The default technique I use is to replace the entire string

 

Instead of grouping the “_” ….. instead group the characters before and after the “_” like this:

(^[^_]*)\_(.*$)

Then replacement string to use in FME is:

\1-\2

ie. Replace the entire string with Group 1 characters (before the “_”) + “-” +  Group 2 characters (after the “_”)


Thank you so much ​@bwn  - that works perfectly!

Really appreciate your help! 


With replacements, I usually use a more explicit form in RegEx to avoid this.  The default technique I use is to replace the entire string

 

Instead of grouping the “_” ….. instead group the characters before and after the “_” like this:

(^[^_]*)\_(.*$)

Then replacement string to use in FME is:

\1-\2

ie. Replace the entire string with Group 1 characters (before the “_”) + “-” +  Group 2 characters (after the “_”)

Great solution!


Just as an FYI, if you are using regex 101 for testing you want to make sure global is enabled, as this is generally how FME is implementing regular expressions

 


Thanks so much for the tip ​@ebygomm - much appreciated! :)