【问题标题】:Check if string is Alphanumeric检查字符串是否为字母数字
【发布时间】:2013-12-28 13:54:36
【问题描述】:

D 中是否有标准函数来检查字符串是否为字母数字?如果不是,那么最有效的方法是什么?我猜有比遍历字符串并检查字符是否在范围之间更好的方法吗?

【问题讨论】:

    标签: string d alphanumeric


    【解决方案1】:

    我不认为它有一个单独的预制函数,但你可以组合两个 phobos 函数(imo 一样好!):

    import std.algorithm, std.ascii;
    bool good = all!isAlphaNum(your_string);
    

    我认为这会进行不必要的 utf 解码,因此它不会最大限度地提高效率,但无论如何这可能与此无关,因为字符串肯定很短。但是,如果这对您很重要,也许您自己使用 .representation(来自 std.string iirc)或 foreach(char c; your_string) isAlphaNum(c); 会快一些。

    【讨论】:

      【解决方案2】:

      我认为 Adam D. Ruppe 的解决方案可能更好,但这也可以使用正则表达式来完成。可以查看正则表达式here的解释。

      import std.regex;
      import std.stdio;
      
      void main()
      {
          // Compile-time regexes are preferred
          // auto alnumRegex = regex(`^[A-Za-z][A-Za-z0-9]*$`);
          // Backticks represent raw strings (convenient for regexes)
          enum alnumRegex = ctRegex!(`^[A-Za-z][A-Za-z0-9]*$`);
          auto testString = "abc123";
          auto matchResult = match(testString, alnumRegex);
      
          if(matchResult)
          {
              writefln("Match(es) found: %s", matchResult);
          }
          else
          {
              writeln("Match not found");
          }
      }
      

      当然,这也只适用于 ASCII。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-18
        • 2015-01-04
        • 1970-01-01
        • 1970-01-01
        • 2013-08-10
        相关资源
        最近更新 更多