LALLB
LALLB

Reputation: 33

How do I use Regex.Replace to replace two dots?

I need to find in a string a pattern with two dots (..) e.g.:

Example 1:

axdb..TXU 

and replace it with

TXU@axdb_LNK

another example would be e.g.:

Example 2

ssrrdb..WOPXLP

and replace it with

WOPXLP@ssrrdb_LNK

It could occur once or many times in the string and there could be any number of letters before or after the double dots. Also, there will be other text in the string. e.g:

SELECT col2 FROM axdb..TXU a WHERE a.col1 = 1 
(could also be select * from axdb..TXU )

would be changed to

SELECT col2 FROM TXU@axdb_LNK a WHERE a.col1 = 1 
(could also be select * from TXU@axdb_LNK)

Upvotes: 3

Views: 1612

Answers (2)

Stephan
Stephan

Reputation: 43053

Try this regex:

(\S+)\.\.(\S+)

Description

Regular expression visualization

Sample code

///<summary>  
///
///  [1]: A numbered capture group. [\S+]
///      Anything other than whitespace, one or more repetitions
///  \.\.
///      Literal .
///      Literal .
///  [2]: A numbered capture group. [\S+]
///      Anything other than whitespace, one or more repetitions
///
///  
///
/// </summary>
public Regex MyRegex = new Regex(
            "(\\S+)\\.\\.(\\S+)",
            RegexOptions.IgnoreCase
            | RegexOptions.CultureInvariant
            | RegexOptions.Compiled
            );

// This is the replacement string
public string MyRegexReplace = "$2@$1_LNK";

//// Replace the matched text in the InputText using the replacement pattern
string result = MyRegex.Replace(InputText,MyRegexReplace);

Upvotes: 2

gpmurthy
gpmurthy

Reputation: 2427

UPDATED:Consider the following code snippet...

string inputMessage = @"SELECT col2 FROM axdb..TXU a WHERE a.col1 = 1 
(could also be select * from axdb..TXU )";
var match = Regex.Match(inputMessage, @"(?<1>\w*)\.\.(?<2>\w*)");
string outputMessage = inputMessage.Replace(match.Value, string.Format("{2}@{1}_LNK", match.Groups[0].Value, match.Groups[1].Value));

Good Luck!

Upvotes: 2

Related Questions