0

空白で囲まれた特定の文字列を文字列で検索したい。たとえば、次の値から true を受け取りたい:

Regex.IsMatch("I like ZaleK", "zalek",RegexOptions.IgnoreCase) 

値 false から:

Regex.IsMatch("I likeZaleK", "zalek",RegexOptions.IgnoreCase)  

これが私のコードです:

Regex.IsMatch(w_all_file, @"\b" + TB_string.Text.Trim() + @"\b", RegexOptions.IgnoreCase) ;

w_all_file に検索対象の文字列があり、その後に「-」が続く場合は機能しません。

例: w_all_file = "I like zalek_" の場合 - 文字列 "zalek" は見つかりませんが、w_all_file = "I like zalek-" の場合 - 文字列 "zalek" が見つかります

理由はありますか?

ありがとう、

ザレック

4

3 に答える 3

0

The \b character in regex doesn't consider an underscore as word boundry. You might want to change it to something like this:

Regex.IsMatch(w_all_file, @"[\b_]" + TB_string.Text.Trim() + @"[\b_]", RegexOptions.IgnoreCase) ;

于 2013-02-15T19:09:26.647 に答える
0

\b matches at a word boundary, which are defined as between a character that is included in \w and one that is not. \w is the same as [a-zA-Z0-9_], so it matches underscores.

So basically, \b will match after the "k" in zalek- but not in zalek_.

It sounds like you want the match to also fail on zalek-, which you can do by using lookaround. Just replace the \b at the beginning with (?<![\w-]), and replace the \b at the end with (?![\w-]):

Regex.IsMatch(w_all_file, @"(?<![\w-])" + TB_string.Text.Trim() + @"(?![\w-])", RegexOptions.IgnoreCase) ;

Note that if you add additional characters to the character class [\w-], you need to make sure that the "-" is the very last character, or that you escape it with a backslash (if you don't it will be interpreted as a range of characters).

于 2013-02-15T19:10:35.380 に答える
0

That's what you need?

string input = "type your name";
string pattern = "your";

Regex.IsMatch(input, " " + pattern + " ");
于 2013-02-15T19:10:57.470 に答える