Reputation: 3
I am fairly new to using regex and I am not entirely clear on the syntax for everything yet. Basically I am stuck on a bit of code where I have:
if(@"\d{2,}\s"+string == Path.GetFileNameWithoutExtension(dir))
{
do stuff
}
My problem is that it won't match anything. I basically have a bunch of files that it's searching through that all have 2 digits and a space, then the name that the user is searching for. Can I combine regex + string like that or is the problem with my regex/statement? Just for clarity, it will match when I actually remove the two digits and space from the files. I apologize if the problem is obvious, I've only been playing with regex for a few days...
Upvotes: 0
Views: 1399
Reputation: 11480
You actually shouldn't have to use a Regular Expression in that instance, in fact that may be over complicating the goal.
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string [] file = Directory.GetFiles(path, @"11_*.txt", SearchOption.AllDirectories);
foreach(string f in file)
{
// Do Something.
}
If your entirely headset on utilizing Regular Expressions, you would do something more along these lines:
using System.Text.RegularExpressions;
...
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var file = Regex.IsMatch(path, @"\d{2,}\2");
if(file == true)
{
// Do Something
}
That is one way to use Regular Expressions, they can be even more powerful with Linq
. I would highly recommend researching this on the MSDN, it has some solid resources.
Upvotes: 0
Reputation: 149030
Your if
statement is not attempting to match a regular expression pattern, it's simply comparing two strings. That's what the Regex.IsMatch
method is for. Also you will probably want to use Regex.Escape
to combine a regex pattern with an arbitrary string.
Try this:
using System.Text.RegularExpressions;
...
var pattern = @"\d{2,}\s" + Regex.Escape(myString);
var fileName = Path.GetFileNameWithoutExtension(dir);
if (Regex.IsMatch(fileName, pattern))
{
// do stuff
}
Upvotes: 3