C#中不区分大小写的搜索功能

时间:2016-03-19 11:06:09

标签: c# regex search datagridview

我想在按钮点击事件后面的DataGridView上创建搜索功能。为此,我使用了以下源代码:

chargerDataGrid();
dg_logiciel.ClearSelection();

string search = txtbox_recherche.Text;
foreach (DataGridViewRow dgvr in dg_logiciel.Rows)
{
    if (!dgvr.Cells[1].Value.ToString().Contains(search))
    {
        dgvr.Visible = false;
    }
}

它正在工作,但我想比较我的两个字符串忽略大小写。为此,我尝试了这段代码:

chargerDataGrid();
dg_logiciel.ClearSelection();

string search = txtbox_recherche.Text;
foreach (DataGridViewRow row in dg_logiciel.Rows)
{
    Regex pattern = new Regex(row.Cells[1].Value.ToString(), RegexOptions.IgnoreCase);
    if (!pattern.IsMatch(search))
    {
        row.Visible = false;
    }
}

根本不起作用。我是否使用了Regex类或其他什么?

2 个答案:

答案 0 :(得分:2)

不幸的是,.NET缺少IndexOf函数重载。

但是您可以轻松地将这样的扩展功能添加到您的项目中,因为我们有一个合适的public static class StringExtensions { public static bool Contains(this string str, string value, StringComparison comparison) { return str.IndexOf(value, comparison) >= 0; } } 重载:

if (!dgvr.Cells[1].Value.ToString().Contains(search, StringComparison.OrdinalIgnoreCase))

然后简单地使用:

CurrentCultureIgnoreCase

或根据您的需要使用search

至于你的正则表达式尝试,显然没有必要这么做,但是由于以下原因的结合,你的尝试失败了:

  • 您反转了搜索的值和搜索的字符串。您必须使用Regex.Escape字符串作为模式构建正则表达式实例。
  • 说到这一点,你应该逃过搜索值。如果它包含任何正则表达式元字符,则该模式将无效。您可以为此目的使用if (!Regex.IsMatch(row.Cells[1].Value.ToString(), Regex.Escape(search), RegexOptions.IgnoreCase))

因此,以下可以使用,但是正确的工作方式:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.denny.protoype2">

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:name="Protoype2"
    android:allowBackup="true"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".Protoype2"
        android:label="@string/title_activity_global_var"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>
</application>

答案 1 :(得分:0)

在您的回答中,以下参数的含义是什么?它将如何工作?

this string str

我的意思是this和静态共存