2012-07-27 2 views
1

Je dois analyser le format suivant @[Alphanumeric1](Alphanumeric2:Alphanumeric3) à partir d'une longue chaîne. Ci-dessous est ma chaîne:Trouver un motif dans une chaîne et le remplacer

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

je besoin de toute l'occurence de (@[Alphanumeric1](Alphanumeric2:Alphanumeric3)) à remplacer par la valeur qui vient après deux points (:)-à-dire que je veux la sortie comme

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

Répondre

0

Cela devrait faire l'affaire:

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]*)\)

Cela correspondra aux trois chaînes ci-dessus, et saisir la chaîne alphanumérique après le : dans le groupe . Play with the regex here.

0

Le regex suivant devrait en mesure de gérer cette entrée:

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

Utilisé en C#, ce qui suit trouvera & remplacer toutes les occurrences dans une chaîne input:

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

Regex Explained:

(       # 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 ')' 
) 
Questions connexes