[英]C# Check if Regex is a match, returns True instead of False
I'm not familiar with Regex so, I hope someone can help me with this.我不熟悉 Regex 所以,我希望有人能帮助我。 I'm using Regex and I'm checking further in the code if that specific Regex is a match or not.
我正在使用正则表达式,我正在进一步检查代码中的特定正则表达式是否匹配。
Regex I use and want to check for:我使用并想检查的正则表达式:
Regex InitialGForKj = new Regex("[Y[\\s\\S]|E[BILPRSY]|I[BELN]]", RegexOptions.Compiled);
. Now the code where I check if it is a match is as followed:现在我检查它是否匹配的代码如下:
else if (i == 0 && InitialGForKj.IsMatch(upperLetters.Substring(1, 3)))
{
dmetaphoneKeyResultPrimary.Append("K");
dmetaphoneKeyResultSecondary.Append("J");
i += 2;
}
i
is the current Character (In this case it is 'G'). i
是当前字符(在这种情况下它是'G')。upperLetters
= The Word what will be checked (In this case: Garçon). upperLetters
= 要检查的字(在本例中:Garçon)。dmetaphoneKeyResultPrimary
and dmetaphoneKeyResultSecondary
are the replacements for the Letter 'G' (Both are Stringbuilders). dmetaphoneKeyResultPrimary
和dmetaphoneKeyResultSecondary
是字母 'G' 的替代品(两者都是 Stringbuilders)。 I Also checked with Console.WriteLine()
what the substring its value is (Which returns "arç").我还检查了
Console.WriteLine()
其值的子字符串是什么(返回“arç”)。 So, now the question is, why does the code see this as true
and not as False
?那么,现在的问题是,为什么代码将其视为
true
而不是False
? Which I think it must be False
.我认为它必须是
False
。
Or am I doing it completely wrong?还是我完全错了?
You must write it as你必须把它写成
var InitialGForKj = new Regex("Y.|E[BILPRSY]|I[BELN]", RegexOptions.Compiled | RegexOptions.Singleline);
See the regex demo .请参阅正则表达式演示。 Note that
.
请注意
.
matches any char including a newline since the RegexOptions.Singleline
option is passed to the Regex constructor.匹配任何字符,包括换行符,因为
RegexOptions.Singleline
选项被传递给Regex构造函数。
The current [Y[\\s\\S]|E[BILPRSY]|I[BELN]]
pattern matches 3 alternatives:当前
[Y[\\s\\S]|E[BILPRSY]|I[BELN]]
模式匹配 3 个选项:
[Y[\\s\\S]
- a Y
, [
, whitespace or non-whitespace (this matches any char there is!) [Y[\\s\\S]
- 一个Y
, [
,空格或非空格(这匹配任何字符!)|
- or E[BILPRSY]
- E
and then one letter from the class E[BILPRSY]
- E
然后是班上的一封信|
- or I[BELN]]
- a I
followed with B
, E
, L
, N
, and then ]
. I[BELN]]
- a I
跟着B
, E
, L
, N
,然后是]
。 As you see, you corrupted it by enclosing the whole pattern with [
and ]
.如您所见,您通过用
[
和]
包围整个模式来破坏它。
First of all, this is your current expression:首先,这是您当前的表达方式:
As you see, the outer [ ] will be recognized as chars.如您所见,外部 [ ] 将被识别为字符。 So drop them!
所以放下他们!
Because \\s\\S is recognised as whitespace or non-whitespace, so pretty much as everything, Garcon is a valid match.因为 \\s\\S 被识别为空白或非空白,所以几乎和所有东西一样,Garcon 是一个有效的匹配项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.