Search Unity

Question Having a string between two special characters

Discussion in 'Scripting' started by marianaloa, Nov 9, 2022.

  1. marianaloa

    marianaloa

    Joined:
    Feb 17, 2021
    Posts:
    15
    Hello, I'm trying to get the string between two special characters and then replace that text with something i need

    I have a string like this "New :north: Game :south:" and i wanna get the north and south thing and replace it with another string i have, but i first need to check if the text have this special characters to then do everything, right know i have too much ifs that do the work but it's not the best way.

    upload_2022-11-9_11-34-24.png
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Bunny83 likes this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    4,004
    A regex like this would probably do:

    Code (CSharp):
    1.         var regExp = new System.Text.RegularExpressions.Regex("\\:(.*?)\\:");
    2.         var str = regExp.Replace("New :north: Game :south:", $"<sprite=\"{spriteSheetName}\" name=\"$1\">");
    3.  
    This single Replace call would replace all your ifs at once. Note that this would replace any string between two colons. So this may cause issues if your text may contain additional colons as well. Though instead of using
    .*?
    (which is a non-greedy(?) wildcard(*) for any character(.)) you could use something more restrictive like
    north|south
    . So only those two words would match.

    If that doesn't solve your problem, there may be other details you haven't mentioned. Note the "$1" in the replace string refers to the first capture group (the things in the parentheses)