Reputation: 564
I want to extract an ID from a string which has the form "somethinguseless_XXXXX ". XXXXX is the ID I need. The string always has the same length and the format won't change over time.
I found 2 solutions to extract the ID => oldAttribute.substring(17,22)
or Regex.Match(oldAttribute,@"_([0-9]{5})").Groups[1].value
.
Which one do you think is better than the other?
Upvotes: 0
Views: 635
Reputation: 3743
int p=5; //length of the substring
string id = oldAttribute.substring(oldAttribute.Length-p, p)
Upvotes: 0
Reputation: 6446
its my suggestion , if the format is same and if "somethinguseless" doesn't contain _ you can use string.split();
Upvotes: 0
Reputation: 252
Go for the second one.
Regex.Match(oldAttribute,@"_([0-9]{5})").Groups[1].value
This will even work in case ur string length before underscore gets changed anyhow.
Upvotes: -1
Reputation: 53989
Personally I'd got for the option 3, split the string based on the underscore.
var id = "somethinguseless_XXXXXX".Split('_')[1];
You'll want to do some better testing to make sure the array is the length you want but this is the approach I'd likely take.
I know you've said that the string will always be the same length and won't change over time, but my experience tells me that things can always change and often aren't always the same.
Upvotes: 1
Reputation: 51
substring is the better option - when you know the location of the ID with in the string.
Upvotes: 0
Reputation: 3883
using Regex
is more flixable than SubString
but I think the performance of SubString
is greater.
Upvotes: 0
Reputation: 77540
If the length is consistent, Substring()
will work just as well and likely perform better. A quick test over a few million iterations would probably verify that assumption.
Upvotes: 2