如何使用Regex.Replace替换两个点?

时间:2013-12-03 23:00:54

标签: c# regex

我需要在字符串中找到一个带有两个点(..)的模式,例如:

示例1:

axdb..TXU 

并将其替换为

TXU@axdb_LNK

另一个例子是例如:

示例2

ssrrdb..WOPXLP

并将其替换为

WOPXLP@ssrrdb_LNK

它可能在字符串中出现一次或多次,并且在双点之前或之后可能有任意数量的字母。此外,字符串中还有其他文本。 e.g:

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

将更改为

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

2 个答案:

答案 0 :(得分:2)

更新:请考虑以下代码段...

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));

祝你好运!

答案 1 :(得分:1)

试试这个正则表达式:

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

描述

Regular expression visualization

示例代码

///<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);