VeecoTech
VeecoTech

Reputation: 2143

Regex to spot characters

Please advise how to get the regex below: I would like to change the word in front of the ".abc_" to john. The word in front can be of any character long.

 material.abc_Inventory    = john.abc_Inventory  
 abx.abc_abxx              = john.abc_abxx  
 stackoverflow.abc_stack   = john.abc_stack

I am able to change if it has the fix character long but not this random word. Please advise

------- Edit below ------
Miss out the requirement below. The regex suggested on below solution highlighted all the text before the keyword including the "insert into" which i do not want.

insert into material.abc_Inventory   = insert into john.abc_Inventory  
insert into material.ABC_Inventory   = insert into john.ABC_Inventory

Upvotes: 0

Views: 92

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Try this:

Console.WriteLine(Regex.Replace("material.abc_Inventory", "^[^.]*[.]abc_", "john.abc_"));

This expression does not let the string preceding the .abc_ contain a dot. If you would like to allow the dot, use "^.*?\[.\]abc_" instead (ideone link).

EDIT: If you must avoid spaces, use a different expression (ideone link):

Console.WriteLine(Regex.Replace("material.abc_Inventory", "^[^. ]*[.]abc_", "john.abc_"));

Now the list of consecutive characters in front of the keyword excludes spaces as well.

Upvotes: 1

Jon Rimmer
Jon Rimmer

Reputation: 12184

You can do this without a regex, should be simpler and faster:

var str = "material.abc_Inventory";

str = "john" + str.Substring(str.IndexOf(".abc_"));

// str == "john.abc_Inventory"

Upvotes: 3

Related Questions