REGEX匹配字符串中与字母相等的数字的计数

时间:2019-04-03 03:00:31

标签: regex

只需检查是否可以使用正则表达式来验证/检查字母数字字符串,以确保其总的数字和字母相同。

例如,

7868HGCD (4 digits, 4 alphabets)
87429AJIGH (5 digits, 5 alphabets)
8A2K9H7A (digits ,alphabets alternately)
1H2B3C7D9K8L

..然后列表继续。

任何语法都可以,只要字符串中的数字和字母总计相等即可。我试过了^([a-zA-Z0-9 -]+)$,它接受​​字母数字,但是我不知道可以用什么正则表达式来检查(总数字=总字母)

使用前瞻^(?=[^\s]?[0-9])(?=[^\s]?[a-zA-Z])[a-zA-Z0-9]*$,但会查找所有至少包含一个字母和一个数字的字符串。

3 个答案:

答案 0 :(得分:1)

我不知道使用纯正则表达式执行此操作的方法,但是如果您将正则表达式与应用程序语言一起使用,则此问题很简单。例如,在Java中,我们可以尝试:

String input = "7868HGCD";
if (input.replaceAll("[A-Z]", "").length() ==
    input.replaceAll("[0-9]", "").length()) {
    System.out.println("match");
}
else {
    System.out.println("no match");
}

这里的想法是使用正则表达式替换字母或数字,然后比较每个字母或数字的剩余长度。

答案 1 :(得分:1)

只需投入两美分即可:您可以为自己编写一个小型解析器,例如在Python中:

from parsimonious.grammar import Grammar
from parsimonious.nodes import NodeVisitor
from parsimonious.exceptions import ParseError

grammar = Grammar(
    r"""
    term        = (digit / alpha)+
    digit       = ~"\d"
    alpha       = ~"[a-zA-Z]"
    """)

class AlnumCounter(NodeVisitor):
    def __init__(self):
        self.reset()

    def reset(self):
        self.abc = 0
        self.digits = 0

    def visit_digit(self, node, children):
        self.digits += 1

    def visit_alpha(self, node, children):
        self.abc += 1

    def visit_term(self, node, children):
        return (self.digits, self.abc)

    def generic_visit(self, node, visited_children):
        return node or visited_children

# list of strings
strings = ['7868HGCD', '87429AJIGH', '8A2K9H7A', '1H2B3C7D9K8L', 'somegarbage', 'parsing error']

alnum = AlnumCounter()
for string in strings:
    try:
        tree = grammar.parse(string)
        out = alnum.visit(tree)

        if out[0] == out[1]:
            print("Correct format: {}".format(string))
        else:
            print("Not correct: {}".format(string))

    except ParseError:
        print("Encountered strange characters within '{}'".format(string))

    finally:
        # reset the counters
        alnum.reset()

这会产生

Correct format: 7868HGCD
Correct format: 87429AJIGH
Correct format: 8A2K9H7A
Correct format: 1H2B3C7D9K8L
Not correct: somegarbage
Encountered strange characters within 'parsing error'

答案 2 :(得分:0)

这是使用JavaScript protected void FindProductBtn_Click(object sender, EventArgs e) { string connectionString1; SqlConnection cnn1; connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; cnn1 = new SqlConnection(connectionString1); string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = (" + Convert.ToInt32(ProductIDTB.Text) + ") "; SqlCommand com1 = new SqlCommand(selectSql1, cnn1); try { cnn1.Open(); using (SqlDataReader read = com1.ExecuteReader()) { while (read.Read()) { String productcategory = Convert.ToString(read["ProductCategory"]); ProductCategoryTB.Text = productcategory; String productname = Convert.ToString(read["ProductName"]); ProductNameTB.Text = productname; String productprice = Convert.ToString(read["ProductPrice"]); ProdPriceTB.Text = productprice; } } } catch (Exception ex) { Response.Write("error" + ex.ToString()); } finally { cnn1.Close(); ProductCategoryTB.ReadOnly = true; ProductNameTB.ReadOnly = true; ProdPriceTB.ReadOnly = true; } } 方法的简单解决方案。

match