我有一串字符串。现在我必须构建一个regex,它给我一个字符串,它以一个字母开头,然后\,然后是4个数字。
我尝试了下面的代码。
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string[] testStrings = new string[] { "w:\WES\1234", "w:\WES\4567", "w:\WES\856432", "w:\WES\AdK1234qw", "w:\WES\abcdesf};
string RegEx = Regex.Escape("\b\d+\w*\b");
foreach(var testString in testStrings)
{
string f = Regex.Escape(testString );
Match match = Regex.Match(f, @RegEx);
// Here we check the Match instance.
if (!match.Success)
{
continue;
}
console.writeline("teststringcorrect", match.value);
}我希望能得到答案。
"w:\WES\1234“和"w:\WES\4567”
如何更改regex模式以找到适合我的字符串?
在Andrew建议的调整之后,编辑了我的代码:
string root = @"C:emp\WES"; // Outputdebug: C:emp\WES
Regex re= new Regex("^" + Regex.Escape(root) + @"\\[0-9]{4}$"); // outputdebug: re.Pattern : ^C:emp\\WES\\[0-9]{4}$
string[] subfolder = Directory.GetDirectories(root); // ouputdebug: {string[4]}. [0]:C:emp\WES\1234 [1]:C:emp\WES\5678 [3]:C:emp\WES\wqder [4]:C:emp\WES\60435632
var dirs = Directory.EnumerateDirectories(root).Where(d => re.IsMatch(d)); // outputdebug: {system.link.Enumerable.WhereEnumarableIteraTOR<STRING>} Current is Null
foreach (var folder in subfolder)
{
string f = Regex.Escape(folder);
Match match = re.Match(f); // outputdebug: groups is 0
// Here we check the Match instance.
if (!match.Success)
{
continue;
}
}发布于 2019-06-26 13:48:36
您不能转义正在检查的字符串(testString),因为这会改变它。
您可以使用@符号将以下字符串变为文字(例如,@"\r"将被视为反斜杠和r,而不是回车字符)。即使这样,regex中的文本反斜杠也需要转义为\\。
要用Console.WriteLine()输出多个字符串,必须将它们与+连接起来。
static void Main(string[] args)
{
string[] testStrings = new string[] { @"w:\WES\1234", @"w:\WES\4567", @"w:\WES\856432", @"w:\WES\AdK1234qw", @"w:\WES\abcdesf"};
Regex re =new Regex(@"^w:\\WES\\[0-9]{4}$");
foreach (var testString in testStrings)
{
Match match = re.Match(testString);
if (match.Success)
{
Console.WriteLine("teststringcorrect " + match.Value);
}
}
Console.ReadLine();
}产出:
teststringcorrect w:\WES\1234
teststringcorrect w:\WES\4567基于此,如果您有一个目录,并且希望找到其中的子目录,其中的名称正好是四位数,您可以这样做:
string root = @"C:\temp";
Regex re = new Regex("^" + Regex.Escape(root) + @"\\[0-9]{4}$");
var dirs = Directory.EnumerateDirectories(root).Where(d => re.IsMatch(d));
Console.WriteLine(string.Join("\r\n", dirs));可能输出的
C:\temp\4321
C:\temp\9876https://stackoverflow.com/questions/56773561
复制相似问题