簡體   English   中英

檢查字符串是否包含字符和數字

[英]Check if string contains character and number

如何檢查字符串中是否包含以下字符“ RM”,后跟任意數字或特殊字符(-,_等),再后跟“ T”?

例如:thisIsaString ABRM21TC =是,包含“ RM”,后跟數字,后跟“ T”

例如:thisIsaNotherString RM-T =是,包含“ RM”,后跟一個特殊字符,然后是“ T”

您將要使用正則表達式(正則表達式)檢查字符串。 有關此操作的信息,請參見此MSDN。

http://msdn.microsoft.com/en-us/library/ms228595.aspx

試試這個正則表達式。

[^RM]*RM[^RMT]+T[^RMT]*

這是一個示例程序。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication12
{
    class Program
    {
        static void Main(string[] args)
        {
            String rg = "[^RM]*RM[^RMT]+T[^RMT]*";
            string input = "111RM----T222";

            Match match = Regex.Match(input, rg, RegexOptions.IgnoreCase);

            Console.WriteLine(match.Success);
        }

    }

}

您可以使用簡單的正則表達式來做到這一點:

var match = Regex.Match(s, "RM([^T]+)T");
  • 通過調用match.Success檢查模式是否存在。
  • 通過調用match.Groups[1]獲取捕獲的值。

這是一個演示(在ideone上: link ):

foreach (var s in new[] {"ABRM21TC", "RM-T", "RxM-T", "ABR21TC"} ) {
    var match = Regex.Match(s, "RM([^T]+)T");
    Console.WriteLine("'{0}' - {1} (Captures '{2}')", s, match.Success, match.Groups[1]);
}

它打印

'ABRM21TC' - True (Captures '21')
'RM-T' - True (Captures '-')
'RxM-T' - False (Captures '')
'ABR21TC' - False (Captures '')

使用正則表達式

http://www.webresourcesdepot.com/learn-test-regular-expressions-with-the-regulator/

調節器是一種先進的免費正則表達式測試和學習工具。 它允許您針對任何文本輸入,文件或Web構建和驗證正則表達式,並在易於理解的分層樹中顯示匹配,拆分或替換的結果。

您應該處理更多示例數據,尤其是有關特殊字符的示例數據,可以使用regexpal,我添加了這兩種情況和一個表達式來幫助您入門

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM