Regular expression replace a word by a link

后端 未结 7 2405
走了就别回头了
走了就别回头了 2020-12-18 11:51

I want to write a regular expression that will replace the word Paris by a link, for only the word is not ready a part of a link.

Example:

    i\'m l         


        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-18 12:28

    You could search for this regular expression:

    (]*>.*?)|Paris
    

    This regex matches a link, which it captures into the first (and only) capturing group, or the word Paris.

    Replace the match with your link only if the capturing group did not match anything.

    E.g. in C#:

    resultString = 
        Regex.Replace(
            subjectString, 
            "(]*>.*?)|Paris", 
            new MatchEvaluator(ComputeReplacement));
    
    public String ComputeReplacement(Match m) {
        if (m.groups(1).Success) {
            return m.groups(1).Value;
        } else {
            return "Paris";
        }
    }
    

提交回复
热议问题