Combining these two Regular Expressions into one

前端 未结 6 1710
眼角桃花
眼角桃花 2020-12-16 17:38

I have the following in C#:

public static bool IsAlphaAndNumeric(string s)
{
    return Regex.IsMatch(s, @\"[a-zA-Z]+\") 
        && Regex.IsMatch(s,         


        
6条回答
  •  心在旅途
    2020-12-16 18:29

    The following is not only faster than the other lookahead constructs, it is also (in my eyes) closer to the requirements:

    [a-zA-Z\d]((?<=\d)[^a-zA-Z]*[a-zA-Z]|[^\d]*\d)
    

    On my (admittedly crude test) it runs in about half the time required by the other regex solutions, and has the advantage that it will not care about newlines in the input string. (And if for some reason it should, it is obvious how to include it).

    Here is how (and why) it works:

    Step 1: It matches a single character (let us call it c) that is a number or a letter.
    Step 2: It does a lookbehind to check if c is a number. If so:
    Step 2.1: It allows an unlimited number of characters that are not a letter, followed by a single letter. If this matches, we have a number (c) followed by a letter.
    Step 2.2: If c is not a number, it must be a letter (otherwise it would not have been matched). In this case we allow an unlimited number of non-digits, followed by a single digit. This would mean we have a letter (c) followed by a number.

提交回复
热议问题