简体   繁体   English

如何为带有字母和数字的搜索模式创建正则表达式?

[英]How to create Regex for search pattern with letter and number?

I am trying to get all the folders inside a given path that match a pattern. 我正在尝试在给定路径内获取与模式匹配的所有文件夹。 The pattern I need is an H with a number that can go from 1 to 9 . 我需要的模式是H ,其数字可以从19

This is how I try to create a regular expression, but it crashes with an "Illegal pattern" exception: 这是我尝试创建正则表达式的方法,但是由于“非法模式”异常而崩溃:

Regex searchPattern = new Regex(@"(H\d +)\");

This is how I get the folders (paths): 这是我获取文件夹(路径)的方式:

List<string> folders = Directory.GetDirectories(path).Where(p => searchPattern.IsMatch(path)).ToList();

How can I create a proper regular expression that matches the letter H with a number? 如何创建将字母H与数字匹配的正确正则表达式?

Could you provide example input? 您能否提供示例输入? If I run this: 如果我运行此命令:

var path = "H3";
var match = Regex.Match(path, "H[1-9]").Success;

if (match)
{
    Console.WriteLine("Match found!");
    Console.ReadKey();
}

I get "Match found!" 我得到“找到匹配!” in console. 在控制台中。 Although, I don't know what your exact input is. 虽然,我不知道您的确切输入是什么。 My answer is based purely on: "The pattern I need is an H with a number that can go from 1 to 9.". 我的回答完全基于:“我需要的模式是H,其数字可以从1到9。”

I try to create the Regular Expression but it crashes (illegal pattern) 我尝试创建正则表达式,但是崩溃(非法模式)

The problem you have is caused by the literal \\ that is at the end of the pattern. 您遇到的问题是由模式末尾的文字\\引起的。 The backslash is an escaping symbol in a regex pattern, and must be followed with some char. 反斜杠是正则表达式模式中的转义符号,并且必须后面跟一些字符。

A pattern that matches H is H and a pattern that matches a digit from 1 to 9 is [1-9] (a positive character class). H匹配的模式为H ,与19的数字匹配的模式为[1-9] (正字符类)。 So, declare it as 因此,将其声明为

var searchPattern = new Regex(@"H[1-9]");

Then, if you declare the variable as p in the lambda part, use p instead of path (the original directory you are searching for subfolders). 然后,如果在lambda部分中将变量声明为p ,请使用p代替path (要搜索子文件夹的原始目录)。

The following code should suit your needs. 以下代码应满足您的需求。 Please note your Lambda was using path instead of the argument p . 请注意,您的Lambda使用的是path而不是参数p

string path = "C:/my-path";
Regex searchPattern = new Regex(@"H\d");
List<string> folders = Directory.GetDirectories(path).Where(p => searchPattern.IsMatch(p)).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM