正则表达式通配符 [英] Regular expression wildcard
问题描述
我刚刚开始使用正则表达式
,这是如此巨大,即使阅读文档后,我似乎无法找到从哪里开始帮助我的问题。
I've just started using Regular Expressions
and this is so overwhelming that even after reading documentation I can't seem to find where to start to help with my problem.
我要一串字符串。
"Project1 - Notepad"
"Project2 - Notepad"
"Project3 - Notepad"
"Untitled - Notepad"
"HeyHo - Notepad"
和我有一个包含一个字符串。外卡
And I have a string containing a wild card.
"* - Notepad"
我需要,如果我比任何这些字符串包含通配符一则返回true。 (使用 Regex.IsMatch()
或类似的东西。)
I would need that if I compare any of these strings with the one containing the wildcard it returns true. (With Regex.IsMatch()
or something like that..)
我通常不要求回答这样,但我无法找到我所需要的。可能有人只是点出我的方向是正确的?
I don't usually asks for answers like that but I just can't find what I need. Could someone just point me out in the right direction ?
推荐答案
通配符 *
等同于正则表达式。*
(贪婪)或。*?
(不贪婪),所以你要执行与string.replace()
第一个
The wildcard *
is equivalent to the Regex pattern ".*"
(greedy) or ".*?"
(not-greedy), so you'll want to perform a string.Replace()
first
string pattern = inputPattern.Replace("*", ".*?");
Regex regex = new Regex(pattern);
编辑:
请记住,如果 inputPattern
包含正则表达式中使用的任何特殊字符,你的模式将发生爆炸。
Keep in mind, that if inputPattern
contains any special character used by Regex, your pattern would explode.
Regex.IsMatch(input, ".NET"); // may match ".NET", "aNET", "?NET", "*NET" and many more
所以你要留意他们(把 \
这些,如的前面。
- > \
)
So you'll want to keep an eye out for them (put a \
in front of those, such as .
-> \.
)
这篇关于正则表达式通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!