簡體   English   中英

正則表達式可選匹配字母數字和符號

[英]Regex optional matching with letters numbers and symbols

我正在尋找具有以下詳細信息的正則表達式模式

  • 不區分大小寫
  • 一次只有 1 個字母有效
  • 字母前面是帶有可選空格的數字
  • 任何符號都是有效的,即%@/-
  • 它不應該匹配 3 個整數2342 34534 2342 但是345345 / 435236 545
  • 模式需要匹配完整的字符串
  • 多個空格和下划線會事先清理掉,不相關

比賽

"1"
"12"
"12 34"
"12 a 34"
"1a"
"54b"
"32 c"
"43-23"
"45 c/34"
"45/34 d"
"67 / 345"
"23a / 56"
"12 / 56B"

只是為了更具體。 以下不應該匹配

"1 3 5"
"34 a a"
"34b s"
"56/v"
"234 / a"
"234a/a"
"34b 456s"
"34b/456s"
"34b / 456s"

我目前的嘗試是^\\d+[\\s]?[az\\W]?[\\s]?[\\W]?[\\s]?\\d+?[az]?$

你可以在這里看到一個演示

盡管我很可能需要多個模式(對於符號兩側的字母),但我的主要問題是試圖獲得? 正常工作,即使用當前模式 ID 期望獲得更多正面

更新

當前正則表達式產生以下結果。

Good list
-------------
False - 1 <= this should match
True - 12 34
True - 12 a 34
False - 1a <= this should match
True - 54b
False - 32 c <= this should match
True - 43-23
True - 45c/34
True - 45/34d
True - 67 / 345
True - 23a / 56
True - 12 / 56b

Bad list
-------------
False - 1 3 5
False - 34 a a
False - 34b s
False - 234a/a
True - 34b 456s <= these are false positives only because they have 2 letters
True - 34b/456s
True - 34b / 456s

忽略誤報,我可以通過創建 2 個模式來修復,我一直在思考為什么當前的正則表達式與指出的那些不匹配。

根據您的描述,我建議采用以下模式:

^\d+\s?(?:\W\s?\d+(?:\s?[a-z])?|(?:\d+\s?)?[a-z]?|[a-z]\s?\W\s?\d+)$

演示

示例代碼:

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

public class Program
{
    public static void Main()
    {
        var goodList = new List<string>{"1", "12", "12 34","12 a 34", "1a", "54b", "32 c", "43-23", "45c/34", "45/34d", "67 / 345", "23a / 56", "12 / 56b"};
        var badList = new List<string>{"1 3 5", "34 a a", "34b s", "234a/a", "34b 456s", "34b/456s", "34b / 456s"};
        var pattern = @"^\d+\s?(?:\W\s?\d+(?:\s?[a-z])?|(?:\d+\s?)?[a-z]?|[a-z]\s?\W\s?\d+)$";
        var regex = new Regex(pattern);
        Console.WriteLine("Good list");
        Console.WriteLine("-------------");
        foreach (var item in goodList)
        {
            Console.WriteLine(string.Format("{0} - {1}", regex.IsMatch(item), item));
        }

        Console.WriteLine();
        Console.WriteLine("Bad list");
        Console.WriteLine("-------------");
        foreach (var item in badList)
        {
            Console.WriteLine(string.Format("{0} - {1}", regex.IsMatch(item), item));
        }
    }
}

你也可以試試這個。

(?im)^(?!(?:\d+\s){2}\d+\s*$)[^a-z\n]*(?:(?:\d\s?)[a-z])?[^a-z\n]*$

.NET regex tester中的Demo,請點擊標簽、 [table][context]了解更多匹配信息。

暫無
暫無

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

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