Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

How to write this regex?

Discussion in 'Scripting' started by Bagazi, Dec 1, 2018.

  1. Bagazi

    Bagazi

    Joined:
    Apr 18, 2018
    Posts:
    609
    I want to to replace the ID and name with new ones in this string -- " p: {ID: 323233434, name: Bson, type: 3}"

    How could I use the regex to replace it by new ones ?

    I try it like this:
    string blockStr = Regex.Replace(blockStr, " p: {ID:([\\s\\S]*,)", "o: {ID:" + id+","); //the lowercase "id" is my valurabe


    but it does not works...
     
  2. Bagazi

    Bagazi

    Joined:
    Apr 18, 2018
    Posts:
    609
    Oops... emoji...
    upload_2018-12-2_1-15-22.png
     
  3. stefan_s_from_h

    stefan_s_from_h

    Joined:
    Nov 26, 2017
    Posts:
    72
    You can test your regular expressions with tools like https://regexr.com/ (online). The matching pattern in your case could be
    @" p: {ID:\s\d*,"


    (Use @"..." for strings that include a lot of backslashes.)

    That being said ...

    Never ever manipulate serialized data structures directly with text manipulation functions! JSON, XML, etc. just look like plain text but this is deceiving and you could be in a lot of pain when you rely on the order of elements and existence of whitespace.

    HOWTO Avoid Being Called a Bozo When Producing XML applies to JSON, too.

    You should use the right tools. In this case a JSON parser that unserializes your data. You then change the data and serialize it again.
     
  4. Bagazi

    Bagazi

    Joined:
    Apr 18, 2018
    Posts:
    609

    Oh... Get it. Thanks very much .. Anyway, what is the matching pattern of numbers ,letters and space, I set it like "\d[0-9a-z]*" but It does not seem working...
     
  5. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    9,900