0

I have a string (an example of its value is {"id":"123241077871_4423423423414"}) and I only require the part with the numbers and the underscore. However, my way of doing it with the String.Replace method doesn't work. Can anyone help me?

This is what I've tried:

Settings.Default["lastid"].ToString().Replace('{"id":"'+"}',null);
It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
Federal09
  • 639
  • 4
  • 9
  • 25
  • 6
    Well that's invalid C# to start with, so you should be getting a compile-time error... It's not a valid string literal. I would suggest avoiding direct string manipulation here anyway - just parse it as JSON and use the parsed value. – Jon Skeet May 19 '13 at 17:16
  • 2
    And for future reference your questions should expand on the way in which something doesn't work. Wrong result? Compiler error? Runtime error? etc. – Chris May 19 '13 at 17:20

5 Answers5

1

Your code should be

Settings.Default["lastid"].ToString().Replace("{\"id\":\"", "").Replace("\"}","");

As Jon Skeet said, currently, it's not a valid string literal. In addition, Replace only searches for one string of text. You can't do both of them in one pass.

Mike Precup
  • 4,148
  • 21
  • 41
1

How about using a real json parser and doing it the right way

var id = JsonConvert.DeserializeAnonymousType(s, new { id = "" }).id;
I4V
  • 34,891
  • 6
  • 67
  • 79
0

Change your code to this :

Settings.Default["lastid"].ToString().Replace("{\"id\":","");
Settings.Default["lastid"].ToString().Replace("\"}\"","");
Saman Gholami
  • 3,416
  • 7
  • 30
  • 71
0

Just in one pass with regex

string test = Settings.Default["lastid"].ToString();
string result = Regex.Replace(test, @"[^0-9_]", @"");
Console.WriteLine(result);

The regex pattern means:

  • match any character NOT included (^) inside the brackets
  • and replace it with an empty string.

As noted by @newStackExchangeInstance in the comments below, the pattern [^0-9_] could be changed in [^\d_] to keep excluded from the replacement also other Unicode Numerical Characters

Steve
  • 213,761
  • 22
  • 232
  • 286
  • Use `[^\d_]` instead. It's better, as it means if he gets some unicode numerical chars, they still count as numbers and are not replaced. – It'sNotALie. May 19 '13 at 17:30
  • @newStackExchangeInstance Sorry, I am not aware of this. Could you point me to an example? – Steve May 19 '13 at 17:32
  • http://stackoverflow.com/questions/6479423/does-d-in-regex-mean-a-digit Look at the top answer. (Sidenote: I know it says python, but it applies to C# as well) – It'sNotALie. May 19 '13 at 17:34
  • @newStackExchangeInstance well, good to know, not of immediate usage for me, but thanks. I will fix my answer with your findings – Steve May 19 '13 at 17:37
0

Try using Regex.

string json = @"{""id"":""123241077871_4423423423414""}" //or whatever your value is
Regex.Match(json, @"{""id"":""(\d+_\d+)""}".Groups[1] //will give you your result
It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103