字符串比较C# - 全字匹配 [英] String compare C# - whole word match

查看:198
本文介绍了字符串比较C# - 全字匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字符串:

string1  = "theater is small"; 
string2 =  "The small thing in the world";

我需要检查天气字符串的是字符串present与否。结果
我可以使用包含的功能,但它可以做整个单词匹配?即它不应该匹配字符串1的战区!

I need to check weather the string "the" is present in the strings or not.
I can use the contains function, but can it do a whole word match? i.e it should not match with "theater" of string1!

推荐答案

最简单的解决方法是使用常规的前pressions和单词边界分隔符 \\ b

The simplest solution is to use regular expressions and the word boundary delimiter \b:

bool result = Regex.IsMatch(text, "\\bthe\\b");

或者,如果你想找到不匹配的市值,

or, if you want to find mismatching capitalisation,

bool result = Regex.IsMatch(text, "\\bthe\\b", RegexOptions.IgnoreCase);

使用System.Text.RegularEx pressons

另外,你可以分割你的文字为单个单词和搜索结果数组。然而,因为它没有足够的拆就空白,这并不总是微不足道的;这会忽略所有的标点和产生错误的结果。一个解决方案是再次使用常规的前pressions,即 Regex.Split

Alternatively, you can split your text into individual words and search the resulting array. However, this isn’t always trivial because it’s not enough to split on white spaces; this would ignore all punctuation and yield wrong results. A solution is to once again use regular expressions, namely Regex.Split.

这篇关于字符串比较C# - 全字匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆