[英]Find a string in a string with special pattern C#
I have a long string in C# and i need to find substrings that look like this: 我在C#中有一个长字符串,我需要找到看起来像这样的子字符串:
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. 我想找到965.435:001和7854.66:006并将其保存到字符串中。
\\d
means "digit" \\d
表示“数字” +
means "one or more" +
表示“一个或多个” \\.
means a literal dot ( .
alone would mean "any character") .
单独表示“任何字符”) \\b
means "word boundary" (start or end of an alphanumeric "word"). \\b
表示“单词边界”(字母数字“单词”的开头或结尾)。 So, your regex would be 因此,您的正则表达式将是
\b\d+\.\d+:\d+\b
In C#: 在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
}
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");
}
}
}
}
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();
}
Something like this: 像这样:
var match = Regex.Match("\d+\.\d+:\d+")
while (match.Success){
numbersList.Add(match.Groups[0])
match = match.NextMatch()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.