[英]How to create a Regex pattern that returns digits after string - C#
I am trying to create a Pattern that returns me results as shows below given list : 我正在尝试创建一个模式,以返回给我的结果,如下所示:
Help # 7256
Help # 83930
ph # 7222
this is a test example
Help # 029299
New # 92929
output : 输出:
Help # 7256
Help # 83930
Help # 029299
Anything that starts with Help following by # sign then followed by 3 , 4 , 5 digit value 以帮助开头,后跟#号,后跟3,4,5位数字的任何值
I tried something like this 我尝试过这样的事情
Regex pattern = new Regex(@"(Help #) (^|\D)(\d{3, 4,5})($|\D)");
Can someone please help me with creating this patten ? 有人可以帮我创建这个图案吗? (in C#)
(在C#中)
/^Help\s*#\s*(\d{3,5})/gm
I should add that this also matches Help # 029299
like specified in the OP, even though it contains 6 characters. 我应该补充一点,即使它包含6个字符,它也可以与OP中指定的
Help # 029299
匹配。
If you only want to match 3 to 5 characters, this will do it: 如果你只想匹配3到5个字符,这将做到这一点:
/^Help\s*#\s*(\d{3,5})\b/gm
Note : If you ONLY want to match " Help[SPACE]#[SPACE]number
", then simply remove all the \\s*
's. 注意 :如果只希望匹配“
Help[SPACE]#[SPACE]number
”,则只需删除所有\\s*
。
A simple solution, assuming that you want to get all lines that starts with Help #
(regardless of what comes after it), and the format of the input file is consistent: 一个简单的解决方案,假设您希望获取以
Help #
开头的所有行(不管后面是什么),并且输入文件的格式是一致的:
if (currentLine.StartsWith(@"Help #"))
{
// Do something with the line
}
String.StartsWith method reference. String.StartsWith方法参考。
If you want regex solution, here is the regex (in literal string): 如果要使用正则表达式解决方案,请使用以下正则表达式(以字符串形式):
@"^Help #\s+(\d+)"
This can be used with Regex.Match(String) . 可以与Regex.Match(String)一起使用 。 You can pick up the number from the capturing group 1. This one will only match line that starts with
Help #
followed by any number of spaces, then at least 1 digit. 您可以从捕获组1中提取号码。此号码只能匹配以
Help #
开头的行,后跟任意数量的空格,然后至少是1位数字。 Note that this regex is only OK to use if you are scanning your file line by line. 请注意,仅当逐行扫描文件时,才可以使用此正则表达式。
If you must limit it to 3-5 digits: 如果必须将其限制为3-5位数字:
@"^Help #\s+(\d{3,5})"
For C#, try this: 对于C#,请尝试以下操作:
var list = new string[] {
"Help", "Help # 7256", "Help # 83930",
"ph # 7222", "this is a test example",
"Help # 029299", "New # 92929",
"Help # 7256 8945", "Help # 83930 8998 787989"
};
// bear in mind that the $ at the end matches only these strings
// if you want it to match something like Help # 1284 12841 0933 SUBJECT HERE"
// then remove the $ from the end of this pattern
const string pattern = @"^(Help)\s#\s(\d{3,6})\s?(\d{3,6})?\s?(\d{3,6})?$";
var regex = new Regex(pattern);
foreach (string s in list)
{
if (regex.Match(s).Success)
Console.WriteLine(s);
}
Console.WriteLine("Done.");
Console.ReadKey();
Outputs: 输出:
Help # 7256
Help # 83930
Help # 029299
Help # 7256 8945
Help # 83930 8998 787989
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.