簡體   English   中英

使用正則表達式匹配包含數字字母和短划線的字符串

[英]Using Regular Expression Match a String that contains numbers letters and dashes

我需要匹配此字符串011Q-0SH3-936729但不345376346asfsdfgsfsdf它必須包含字符和數字和短划線

模式可以是011Q-0SH3-936729011Q-0SH3-936729-SDF3000-222-AAAA011Q-0SH3-936729-011Q-0SH3-936729-011Q-0SH3-936729-011Q-0SH3-936729我想要它能夠匹配任何人。 原因是我不知道格式是否已修復且我無法找到,所以我需要為具有任意數量的破折號的模式提出通用解決方案,並且模式會重復出現任意數量的倍。

對不起,這可能是一個愚蠢的問題,但我真的很喜歡正則表達式。

TIA

foundMatch = Regex.IsMatch(subjectString, 
    @"^             # Start of the string
    (?=.*\p{L})     # Assert that there is at least one letter
    (?=.*\p{N})     # and at least one digit
    (?=.*-)         # and at least one dash.
    [\p{L}\p{N}-]*  # Match a string of letters, digits and dashes
    $               # until the end of the string.", 
    RegexOptions.IgnorePatternWhitespace);

應該做你想做的事。 如果用字母/數字表示“只有ASCII字母/數字”(也不是國際/ Unicode字母),那么請使用

foundMatch = Regex.IsMatch(subjectString, 
    @"^             # Start of the string
    (?=.*[A-Z])     # Assert that there is at least one letter
    (?=.*[0-9])     # and at least one digit
    (?=.*-)         # and at least one dash.
    [A-Z0-9-]*      # Match a string of letters, digits and dashes
    $               # until the end of the string.", 
    RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);

編輯:

這將匹配您的評論中提供的任何密鑰:

^[0-9A-Z]+(-[0-9A-Z]+)+$

這意味着鑰匙以數字或字母開頭,並且有一個短划線符號:

最天真的實施EVER(可能會讓你開始):

([0-9]|[A-Z])+(-)([0-9]|[A-Z])+(-)([0-9]|[A-Z])+

經過Regex Coach測試。

編輯:

這確實只匹配三組; 在這里另一個,稍好一點:

([0-9A-Z]+\-)+([0-9A-Z]+)

如果沒有關於短划線或其他方面的規律性的更多信息,這是我們能做的最好的事情:

Regex.IsMatch(input,@"[A-Z0-9\-]+\-[A-Z0-9]")

雖然這也符合-A-0

您是否正在將正則表達式應用於整個字符串(即驗證或過濾)? 如果是這樣,蒂姆的回答應該是正確的。 但是如果你從一個更大的字符串中提取匹配項,它會變得更復雜一些。 這是我將如何做到這一點:

string input = @"Pattern could be 011Q-0SH3-936729 or 011Q-0SH3-936729-SDF3 or 000-222-AAAA or 011Q-0SH3-936729-011Q-0SH3-936729-011Q-0SH3-936729-011Q-0SH3-936729 but not 345-3763-46 or ASFS-DFGS-FSDF or ASD123FGH987.";

Regex pluckingRegex = new Regex(
    @"(?<!\S)         # start of 'word'
      (?=\S*\p{L})    # contains a letter
      (?=\S*\p{N})    # contains a digit
      (?=\S*-)        # contains a hyphen
      [\p{L}\p{N}-]+  # gobble up letters, digits and hyphens only
      (?!\S)          # end of 'word'
    ", RegexOptions.IgnorePatternWhitespace);

foreach (Match m in pluckingRegex.Matches(input))
{
  Console.WriteLine(m.Value);
}

輸出:

011Q-0SH3-936729
011Q-0SH3-936729-SDF3
000-222-AAAA
011Q-0SH3-936729-011Q-0SH3-936729-011Q-0SH3-936729-011Q-0SH3-936729

負lookarounds作為“字”的界限:他們確保匹配的子字符串開始或者在字符串的開頭或空白字符(后(?<!\\S)並且無論是在字符串的結束或之前結束空白字符( (?!\\S) )。

三個正面的前瞻就像Tim一樣,除了他們使用\\S*跳過第一個字母/數字/連字符之前的任何內容。 在這種情況下,我們不能使用.*因為這將允許它跳到下一個單詞,或者下一個單詞等,從而破壞前瞻的目的。

暫無
暫無

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

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