简体   繁体   中英

How can I find string in quote using Regular Expression?

I have a text which include this:

  "id": "100001470360923", 
  "name": "Đặng Minh Khiêm", 
  "first_name": "Đặng Minh", 
  "last_name": "Khiêm", 
  "link": "https://www.facebook.com/mrkhiem97", 
  "username": "mrkhiem97", 
  "birthday": "10/09/1992", 
  "location": {
          "id": "108458769184495", 
          "name": "Ho Chi Minh City, Vietnam"
      }, 

I am trying to use Regular Expression in C# to get 2 strings: "id": "100001470360923" "name": "Đặng Minh Khiêm"

        String patternID = "\"id\":\"\\d+\"";
        String patternName = "\"name\":\"[\\w]+\"";
        Match matchID = Regex.Match(data, patternID);
        Match matchName = Regex.Match(data, patternName);

But it doesn't work with patternName

I don't know how to use pattern. Can someone give me pattern for this ?

Your regular expression isn't working because you have non-word characters (like space) in your name. You could just match anything that isn't a quote, using [^\\"]+ . Here's a full example:

String data = "\"id\": \"100001470360923\", \"name\": \"Ð?ng Minh Khiêm\", \"first_name\": \"Ð?ng Minh\", \"last_name\": \"Khiêm\", \"link\": \"https://www.facebook.com/mrkhiem97\", \"username\": \"mrkhiem97\", \"birthday\": \"10/09/1992\", \"location\": { \"id\": \"108458769184495\", \"name\": \"Ho Chi Minh City, Vietnam\" },";
String patternID = "\"id\": \"[^\\\"]+\"";
String patternName = "\"name\": \"[^\\\"]+\"";
Match matchID = Regex.Match(data, patternID);
Match matchName = Regex.Match(data, patternName);

Console.WriteLine(matchID.Value);
Console.WriteLine(matchName.Value);

This outputs:

"id": "100001470360923"
"name": "Ð?ng Minh Khiêm"

Of course if this is some other format (it looks very similar to JSON), it would be easier for you to use a library that is intended for parsing that format. Have a look at DataContractJsonSerializer , or a similar class.

try this one:

var pattern = "\"id\":\\s*\"(?<id>[^\"]*)\"\\s*,\\s*\"name\"\\s*:\\s*\"(?<name>[^\"]*)\"";
var match = Regex.Match(strInput, pattern);
var id = match.Groups["id"].Value;
var name = match.Groups["name"].Value;

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