子串继续搜索直到特定字符

时间:2016-09-02 19:11:27

标签: c# .net string linq substring

我在运行时收到一个字符串。该字符串采用JSON格式(键值对)。其中一个关键是“userId”。我需要检索userId的值。问题是我不知道“{"name":"XX", "userId":"YYY","age":"10"}”键的位置。该字符串可能看起来像{"age":"10", "name":"XX", "userId":"YYY"},或者看起来像{"age":"10"},或者看起来像substring()

我正在考虑使用var index = myString.IndexOf("userId\":\""); if(index != -1){ myString.Subtring(index, ???)//How to specify the length here }

"

我不确定,怎么说继续直到找到下一个set.seed(10) AgeA <- round(rnorm(100, mean = 40, sd = 15)) SexA <- sample(c("M","F"), 100, replace = TRUE, prob = c(0.5, 0.5)) Test_ValueA <- rbinom(100, 1, 0.3) set.seed(20) AgeB <- round(rnorm(1000, mean = 50, sd = 15)) SexB <- sample(c("M","F"), 1000, replace = TRUE, prob = c(0.5, 0.5)) Test_ValueB <- rbinom(1000, 1, 0.4) A <- data.frame(Age = AgeA, Sex = SexA, Test = Test_ValueA) B <- data.frame(Age = AgeB, Sex = SexB, Test = Test_ValueB) genderA<-(prop.table(table(A[,2]))) TestA<-(prop.table(table(A[,3]))) paste("median age in group A is",median(A[,1]), "percentage female in group A is",genderA[1], "percentage of test positive in A is", TestA[2]) genderB<-(prop.table(table(B[,2]))) TestB<-(prop.table(table(B[,3]))) paste("median age in group A is",median(B[,1]), "percentage female in group B is",genderB[1], "percentage of test positive in A is", TestB[2]) (双引号)

3 个答案:

答案 0 :(得分:1)

如果计划仅使用userId属性,则可以简单地声明具有userId成员的对象并反序列化json。在反序列化期间将省略任何其他属性。

class UserIDObj
{
   public string UserId { get; set; }
}

var obj = JsonConvert.DeserializeObject<UserIDObj>("{\"name\":\"XX\", \"userId\":\"YYY\",\"age\":\"10\"}");
string usrID = obj.UserId;

答案 1 :(得分:0)

@WiktorStribiżew给出的答案也像魅力一样。我正在粘贴他的解决方案。

System.Text.RegularExpressions.Regex.Match(myString, "\"userId\":\"([^\"]+)").Groups[1].Value

答案 2 :(得分:-2)

你可以这样做:

var needle = "\"userId\":"; // also you forgot to escape the quote here
var index = myString.IndexOf(needle); 
if(index != -1){
  var afterTheUserId = myString.Substring(index + needle.Length);
  var quoteIndex = afterTheUserId.IndexOf('"');
  // do what you want with quoteIndex
}

但正如Eric Philips和PhonicUK所说,你应该使用一个合适的JSON解析器,而不是编写自己的字符串函数。