简体   繁体   中英

C# how to check if string contains a string combine with changeable value

Currently I'm writing:

    string[] ReadText = File.ReadAllLines(_FILE);
    for(int idx = 0; idx < ReadText.Length; idx++)
    {
        if (ReadText[idx].Contains("BANK0")
        || ReadText[idx].Contains("BANK1")
        || ReadText[idx].Contains("BANK2")
        || ReadText[idx].Contains("BANK3")
        || ReadText[idx].Contains("BANK4")
        || ReadText[idx].Contains("BANK5")
        || ReadText[idx].Contains("BANK6")
        || ReadText[idx].Contains("BANK7")
        || ReadText[idx].Contains("BANK8")
        || ReadText[idx].Contains("BANK9")
        || ReadText[idx].Contains("BANK10")
        || ReadText[idx].Contains("BANK11")
        || ReadText[idx].Contains("BANK12")
        || ReadText[idx].Contains("BANK13")
        || ReadText[idx].Contains("BANK14")
        || ReadText[idx].Contains("BANK15")
        || etc.)
    }

It's terrible if i want to check from BANK0 to BANK255. Is there a method like:

    if (ReadText[idx].Contains(string.format("BANK{0}",[0-255]))

Thanks in advance.

Regex can help you:

//this will match exact the BANKx to BANK255
var isMatch = Regex.Matches(ReadText[idx], "BANK([12]([0-4]\\d|5[0-5])|\\d{1,2})").Count > 0;
//then check for if(isMatch) ...

If there is no restriction to the xxx in BANKxxx (for example, BANK555 is OK), we can use a simpler pattern:

var isMatch = Regex.Matches(ReadText[idx], "BANK\\d+").Count > 0;

A simple function like this will work:

Private Function strContains(input As String) As Boolean
    If input.Contains("Bank") Then
        Dim temp As Integer = -1
        If Integer.TryParse(input.Substring(4), temp) AndAlso temp > -1 Then
            Return True
        End If
    End If
    Return False
End Function

If strContains(ReadText[idx]) Then

End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM