Reputation: 1520
I have the following string fromat:
session=11;reserID=1000001
How to get string array of number?
My code:
var value = "session=11;reserID=1000001";
var numbers = Regex.Split(value, @"^\d+");
Upvotes: 0
Views: 689
Reputation: 11
var numbers = Regex.Split(value, @".*?(.\d+).*?");
or to return each digit:
var numbers = Regex.Split(value, @".*?(\d).*?");
Upvotes: 0
Reputation: 607
I will re-use my code from another question:
private void button1_Click(object sender, EventArgs e)
{
string sauce = htm.Text; //htm = textbox
Regex myRegex = new Regex(@"[0-9]+(?:\.[0-9]*)?", RegexOptions.Compiled);
foreach (Match iMatch in myRegex.Matches(sauce))
{
txt.AppendText(Environment.NewLine + iMatch.Value);//txt= textbox
}
}
If you want to play around with regex here is a good site: http://gskinner.com/RegExr/ They also have a desktop app: http://gskinner.com/RegExr/desktop/ - It uses adobe air so install that first.
Upvotes: 0
Reputation: 8337
.Net has built in feature without using RegEx.Try System.Web.HttpUtility.ParseQueryString
, passing the string. You would need to reference the System.Web
assembly, but it shouldn't require a web context.
var value = "session=11;reserID=1000001";
NameValueCollection numbers =
System.Web.HttpUtility.ParseQueryString(value.Replace(";","&"));
Upvotes: 0
Reputation: 120420
Regex
.Matches("session=11;reserID=1000001", @"\d+") //match all digit groupings
.Cast<Match>() //promote IEnumerable to IEnumerable<Match> so we can use Linq
.Select(m => m.Value) //for each Match, select its (string) Value
.ToArray() //convert to array, as per question
Upvotes: 1
Reputation: 354456
You probably were on the right track but forgot the character class:
Regex.Split(value, @"[^\d]+");
You can also write it shorter by using \D+
which is equivalent.
However, you'd get an empty element at the start of the returned array, so caution when consuming the result. Sadly, Regex.Split() doesn't have an option that removes empty elements (String.Split
does, however). A not very pretty way of resolving that:
Regex.Replace(value, @"[^\d;]", "").Split(';');
based on the assumption that the semicolon is actually the relevant piece where you want to split.
Quick PowerShell test:
PS> 'session=11;reserID=1000001' -replace '[^\d;]+' -split ';'
11
1000001
Another option would be to just skip the element:
Regex.Split(...).Skip(1).ToArray();
Upvotes: 2