2012-07-27 56 views
1

我需要从长字符串中解析以下格式@[Alphanumeric1](Alphanumeric2:Alphanumeric3)。下面是我的字符串:查找字符串中的模式并将其替换

This is a long text 
@[Alphanumeric1](Alphanumeric2:Alphanumeric3) again long text 
@[Alphanumeric11](Alphanumeric22:Alphanumeric33) again long text 
@[Alphanumeric111](Alphanumeric222:Alphanumeric333) 

我需要的(@[Alphanumeric1](Alphanumeric2:Alphanumeric3))所有的发生由其中冒号后的值来代替(:)即我想要的输出

This is a long text 
Alphanumeric3 again long text 
Alphanumeric33 again long text 
Alphanumeric333 

回答

0

这应该是诀窍:

class Program 
{ 
    static void Main(string[] args) 
    { 
     string data = @"This is a long text 
@[Alphanumeric1](Alphanumeric2:Alphanumeric3) again long text 
@[Alphanumeric11](Alphanumeric22:Alphanumeric33) again long text 
@[Alphanumeric111](Alphanumeric222:Alphanumeric333)"; 

     Debug.WriteLine(ReplaceData(data)); 
    } 

    private static string ReplaceData(string data) 
    { 
     return Regex.Replace(data, @"@\[.+?\]\(.*?:(.*?)\)", match => match.Groups[1].ToString()); 
    } 
} 
2

@\[[\w\d]*\]\([\w\d]*:([\w\d]*)\)

这将匹配上面的三个字符串,并在:组之后抓取字母数字字符串。 Play with the regex here

0

下面的正则表达式应该由能够处理输入:

(@\[[a-zA-Z0-9]+\]\([a-zA-Z0-9]+:(?<match>[a-zA-Z0-9]+)\)) 

用在C#中,下面会发现&替换所有实例的字符串input

string output = Regex.Replace(input, @"(@\[[a-zA-Z0-9]+\]\([a-zA-Z0-9]+:(?<match>[a-zA-Z0-9]+)\))", "${match}"); 

正则表达式解释:

(       # beginning of group to find+replace 
    @      # match the '@' 
    \[      # match the '[' 
     [a-zA-Z0-9]+  # alpha-numeric match 
    \]      # match the ']' 
    \(      # match the '(' 
     [a-zA-Z0-9]+  # alpha-numeric match 
     :     # match the ':' 
     (?<match>   # beginning of group to use for replacement 
      [a-zA-Z0-9]+ # alpha-numeric match 
     ) 
    \)      # match the ')' 
) 
相关问题