简体   繁体   中英

Extracting an unknown string between two known strings

I have the following string:

string nextEvent = "[[\"nextData\", \"RANDOM MESSAGE\"], [\"moreInfo\", {\"num\": 3204}]]"

I need to get "RANDOM MESSAGE" (without the quotes) into a seperate string. Now, it would be easy if RANDOM MESSAGE was a constant, but it's not. Let's say that it's generated through user input, and is different in value and length every time.

How would I go about extracting that message from there? I've tried using Substring with IndexOf, but I got wrong results every time, it's quite confusing.

You can use regex to get it:

string input = "[[\\\"nextData\\\", \\\"RANDOM MESSAGE\\\"], [\\\"moreInfo\\\", {\\\"num\\\": 3204}]]";
string pattern = "^\\[\\[\\\\\"nextData\\\\\",\\s*\\\\\"(?<message>[\\S ]+)\\\\\"\\],\\s*\\[\\\\\"moreInfo\\\\\",\\s*\\{\\\\\"num\\\\\":\\s*\\d+\\}\\]\\]$";
Regex r1 = new Regex(pattern);

Match match = r1.Match(input);
if (match.Success)
    Console.WriteLine(match.Groups["message"].Value);

If you'd like a 'brute force' method:

String nextEvent = "[[\"nextData\", \"RANDOM MESSAGE\"], [\"moreInfo\", {\"num\": 3204}]]";
String tmp = nextEvent.Trim(new Char[] { '[', ']' });
String[] sa = tmp.Split(',');
String rndMsg = sa[1].Trim().Trim(new Char[] { '[', ']', '\"' });

you can use simple splits like this:

  string nextEvent = "[[\"nextData\", \"RANDOM MESSAGE\"], [\"moreInfo\", {\"num\": 3204}]]";
  var strs = nextEvent.Split(']');
  var ds = strs[0].Split(',');
  var m = ds[1].TrimStart('"', ' ');
  m = m.TrimEnd('"');

The third possible solution, although not very performing is this:

Take you string and parse it as a Dictionary:

String nextEvent="[[\"nextData\",\"RANDOM MESSAGE\"],[\"moreInfo\",{\"num:\": 3204}]]";
Dictionary<string, object> dict =  JSON.Parse<Dictionary<string,object>>(nextEvent);
String randomMessage = dict("nextData");

this becomes relevant, when you have a very long string in this format and have to extract multiple "fields" from it

If the strings before/after are constant you can get the random message part simply by doing:

int startIndex = ("[[\"nextData\", \"").Length; 
int endIndex = nextEvent.IndexOf(", [\"moreInfo\""); 
string randomMessage = nextEvent.Substring(startIndex, endIndex - startIndex );

You might also use Split to get a string starting from the target area:

string[] temp = nextEvent.Split(new string[] { "[[\"nextData\", \"" }, StringSplitOptions.None);
//temp[1] = "RANDOM MESSAGE..."

Using JSON.NET

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

class Test
{
    static void Main()
    {            
       string nextEvent = "[[\"nextData\", \"RANDOM MESSAGE\"], [\"moreInfo\", {\"num\": 3204}]]";
       JObject json = JObject.Parse("{\"j\":" + nextEvent + "}");
       string randomMessage = (string)json["j"][0][1]; 
       Console.WriteLine(randomMessage); // gives "RANDOM MESSAGE"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM