检查字符串是否为字母数字

时间:2013-12-28 13:54:37

标签: string d alphanumeric

D中是否有标准功能来检查字符串是否为字母数字?如果不是最有效的方法呢?我猜有更好的方法而不是循环遍历字符串并检查字符是否在一个范围之间?

2 个答案:

答案 0 :(得分:7)

我认为没有一个预先制作的功能,但你可以编写两个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);你自己会更快一些。

答案 1 :(得分:4)

我认为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。

相关问题