Reputation: 2592
I have a long string in C# and i need to find substrings that look like this:
number.number:number
For example this string:
text text
965.435:001 text text sample
7854.66:006 text text
I want to find and save 965.435:001 and 7854.66:006 to a string somehow.
Upvotes: 0
Views: 542
Reputation: 2073
the below in an example how to use regex to find certain formats within a string
class TestRegularExpressionValidation
{
static void Main()
{
string[] numbers =
{
"123-456-7890",
"444-234-22450",
"690-203-6578",
"146-893-232",
"146-839-2322",
"4007-295-1111",
"407-295-1111",
"407-2-5555",
};
string sPattern = "^\\d{3}-\\d{3}-\\d{4}$";
foreach (string s in numbers)
{
System.Console.Write("{0,14}", s);
if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern))
{
System.Console.WriteLine(" - valid");
}
else
{
System.Console.WriteLine(" - invalid");
}
}
}
}
Upvotes: 1
Reputation: 2208
Something like this:
var match = Regex.Match("\d+\.\d+:\d+")
while (match.Success){
numbersList.Add(match.Groups[0])
match = match.NextMatch()
}
Upvotes: 0
Reputation: 4572
use a regex and capture the thing..
play with this code... it should get you what you want...
string text = "your text";
string pat = @"(\d*\.\d*:\d*)";
// Instantiate the regular expression object.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
int matchCount = 0;
while (m.Success)
{
Console.WriteLine("Match"+ (++matchCount));
for (int i = 1; i <= 2; i++)
{
Group g = m.Groups[i];
Console.WriteLine("Group"+i+"='" + g + "'");
CaptureCollection cc = g.Captures;
for (int j = 0; j < cc.Count; j++)
{
Capture c = cc[j];
System.Console.WriteLine("Capture"+j+"='" + c + "', Position="+c.Index);
}
}
m = m.NextMatch();
}
Upvotes: 0
Reputation: 336158
\d
means "digit"+
means "one or more"\.
means a literal dot (.
alone would mean "any character")\b
means "word boundary" (start or end of an alphanumeric "word").So, your regex would be
\b\d+\.\d+:\d+\b
In C#:
MatchCollection allMatchResults = null;
Regex regexObj = new Regex(@"\b\d+\.\d+:\d+\b");
allMatchResults = regexObj.Matches(subjectString);
if (allMatchResults.Count > 0) {
// Access individual matches using allMatchResults.Item[]
} else {
// Match attempt failed
}
Upvotes: 7