我的文字包括:
"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"
},
我试图在C#中使用正则表达式来获取2个字符串: “id”:“100001470360923” “名字”:“ĐặngMinhKhiêm”
String patternID = "\"id\":\"\\d+\"";
String patternName = "\"name\":\"[\\w]+\"";
Match matchID = Regex.Match(data, patternID);
Match matchName = Regex.Match(data, patternName);
但它不适用于patternName
我不知道如何使用模式。有人可以给我模式吗?
答案 0 :(得分:1)
您的正则表达式无效,因为您的名字中包含非单词字符(如空格)。您可以使用[^\"]+
匹配任何非引号的内容。这是一个完整的例子:
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);
输出:
"id": "100001470360923"
"name": "Ð?ng Minh Khiêm"
当然,如果这是其他格式(它看起来与JSON非常相似),那么您将更容易使用用于解析该格式的库。看看DataContractJsonSerializer或类似的课程。
答案 1 :(得分:0)
试试这个:
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;