How to transpose a word using Regular expression search and replace

  • Thread starter Babu Mannaravalappil
  • Start date
B

Babu Mannaravalappil

Hi,

I want to replace some words in my text files (actually transpose).
For example, I have a whole lot of expressions (words) in my files as
follows:

TABLECUSTOMERS
TABLEORDERS
TABLEORDERLINES
....
....
....

I want to replace them as follows:

CUSTOMERSTABLE
ORDERSTABLE
ORDERLINESTABLE
....
....
....

How can I do this using regular expression search and repalce?

Babu.
 
C

Chris R. Timmons

(e-mail address removed) (Babu Mannaravalappil) wrote in
Hi,

I want to replace some words in my text files (actually
transpose). For example, I have a whole lot of expressions
(words) in my files as follows:

TABLECUSTOMERS
TABLEORDERS
TABLEORDERLINES

I want to replace them as follows:

CUSTOMERSTABLE
ORDERSTABLE
ORDERLINESTABLE

How can I do this using regular expression search and repalce?

Babu,

Use a pattern of "\bTABLE(.*?)\b", and a replacement string of
"$1TABLE".

Here's an example in C#:


using System;
using System.Text.RegularExpressions;

namespace Main
{
public class MainClass
{
[STAThread]
public static int Main()
{
string input = @"
TABLECUSTOMERS
TABLEORDERS
TABLEORDERLINES
";

Console.WriteLine(SwapWords(input, "TABLE"));

return 0;
}

public static string SwapWords(
string input,
string word)
{
return Regex.Replace(input, "\\b" + word + "(.*?)\\b",
"$1" + word, RegexOptions.Singleline);
}
}
}
 
B

Babu Mannaravalappil

That was quick! Thanks a lot Chris.

Babu.

Chris R. Timmons said:
(e-mail address removed) (Babu Mannaravalappil) wrote in
Hi,

I want to replace some words in my text files (actually
transpose). For example, I have a whole lot of expressions
(words) in my files as follows:

TABLECUSTOMERS
TABLEORDERS
TABLEORDERLINES

I want to replace them as follows:

CUSTOMERSTABLE
ORDERSTABLE
ORDERLINESTABLE

How can I do this using regular expression search and repalce?

Babu,

Use a pattern of "\bTABLE(.*?)\b", and a replacement string of
"$1TABLE".

Here's an example in C#:


using System;
using System.Text.RegularExpressions;

namespace Main
{
public class MainClass
{
[STAThread]
public static int Main()
{
string input = @"
TABLECUSTOMERS
TABLEORDERS
TABLEORDERLINES
";

Console.WriteLine(SwapWords(input, "TABLE"));

return 0;
}

public static string SwapWords(
string input,
string word)
{
return Regex.Replace(input, "\\b" + word + "(.*?)\\b",
"$1" + word, RegexOptions.Singleline);
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top