我在C#中有一个长字符串,我需要找到如下所示的子字符串:
number.number:number
例如这个字符串:
text text
965.435:001 text text sample
7854.66:006 text text
我想以某种方式找到并将965.435:001和7854.66:006保存到字符串中。
答案 0 :(得分:7)
\d
表示“数字”+
表示“一个或多个”\.
表示字面点(.
单独表示“任何字符”)\b
表示“字边界”(字母数字“字”的开头或结尾)。所以,你的正则表达式将是
\b\d+\.\d+:\d+\b
在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
}
答案 1 :(得分:1)
以下示例中如何使用正则表达式查找字符串中的某些格式
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");
}
}
}
}
答案 2 :(得分:0)
使用正则表达式捕获事物..
玩这个代码......它应该能得到你想要的东西......
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();
}
答案 3 :(得分:0)
这样的事情:
var match = Regex.Match("\d+\.\d+:\d+")
while (match.Success){
numbersList.Add(match.Groups[0])
match = match.NextMatch()
}