Search Unity

[Regex] How to replace matched words with same words wrapped in color?

Discussion in 'Scripting' started by UserNobody, Oct 9, 2019.

  1. UserNobody

    UserNobody

    Joined:
    Oct 3, 2019
    Posts:
    144
    Hello everybody :)
    I am trying to solve this one issue, but with no luck so far. I use Regex to find word matches and I want to replace those found words with same words, but wrapped with rich text color tag.

    Example input:
    var newValue = "Hello World";
    Find match: "Hello World".
    And I want to replace that with <color=green>"Hello World"</color>

    I use different patterns to locate and replace different kind of word matches, this is one of the pattern I use. It's easy if I know the word that I'm trying to find, like in below example
    Code (CSharp):
    1. string[] types = new string[6] { "Color", "Color32", "Vector2", "Vector3", "GameObject", "MonoBehaviour" };
    2.  
    3. for (int i = 0; i < types.Length; i++)
    4. {
    5.     Regex keyword = new Regex($@"\b{types[i]}\b");
    6.     c = keyword.Replace(c, WrapText(types[i], Color.green));
    7. }
    But in case when I don't know what I'm going to find, it becomes a bit more complicated.
    Like this pattern, that locates all words that begin and end with quotation marks.
    Regex stringPattern = new Regex("\".+?\"");
    How do I replace found matches in the case like this? Can someone help me with this? :)
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    I haven't done this before, but it looks like Regex.Replace allows you to supply a function that determines what the replacement should be based on the match found. Take a look at this page, particularly the first example (involving WordScrambler).
     
    UserNobody and Suddoha like this.
  3. UserNobody

    UserNobody

    Joined:
    Oct 3, 2019
    Posts:
    144
    Wow, thank you! This is exactly what I needed! :)
     
    Joe-Censored likes this.
  4. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    You can query the matches for a given Regex & text.
    Then, just iterate the matches (a collection of match objects) and replace the findings. You also get additional information that are contained within the returned match objects, such as index and length etc

    EDIT
    Updated the link, as I copied the wrong link which was for the Match (singular) method.
     
    Last edited: Oct 9, 2019
    UserNobody likes this.