简体   繁体   English

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

[英]Check if string is Alphanumeric

Is there a standard function in D to check if a string is alphanumeric? D中是否有标准功能来检查字符串是否为字母数字? If not what'd be the most efficient way to do it? 如果不是,最有效的方法是什么? I'm guessing there are better ways than looping through the string and checking if the character is in between a range? 我猜有比遍历字符串和检查字符是否在范围内更好的方法吗?

I don't think there's a single pre-made function for it, but you could compose two phobos functions (which imo is just as good!): 我不认为它有一个单一的预制函数,但是您可以组成两个phobos函数(imo一样好!):

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

I think that does unnecessary utf decoding, so it wouldn't be maximally efficient but that's likely irrelevant for this anyway since the strings are surely short. 我认为这会执行不必​​要的utf解码,因此不会达到最大的效率,但是由于字符串肯定很短,因此无论如何这都无关紧要。 But if that matters to you perhaps using .representation (from std.string iirc) or foreach(char c; your_string) isAlphaNum(c); 但是,如果这对你很可能使用.representation (从std.string IIRC)或foreach(char c; your_string) isAlphaNum(c); yourself would be a bit faster. 你自己会快一点。

I think Adam D. Ruppe's solution may be a better one, but this can also be done using regular expressions. 我认为Adam D. Ruppe的解决方案可能是更好的解决方案,但这也可以使用正则表达式来完成。 You can view an explanation of the regular expression 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");
    }
}

Of course, this only works for ASCII as well. 当然,这也仅适用于ASCII。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查字符串是否为长度为 1 到 5 的字母数字 - Check that String is alphanumeric with length 1 to 5 在 Swift 中检查字符串是否为字母数字 - Check if a String is alphanumeric in Swift 如何检查字符串是否为字母数字? - How to check if a string is alphanumeric? 有没有办法检查字符串是否是erlang中的字母数字 - Is there a way to check if a string is alphanumeric in erlang Ada字母数字,字符串索引检查失败,运行时错误 - Ada alphanumeric, string index check failed, runtime error javascript检查字符串是否仅包含字母数字字符+其他特殊字符 - javascript check if string contains only alphanumeric characters + other special characters 如何检查字符串中是否只包含目标C中的字母数字字符? - How to check if a string only contains alphanumeric characters in objective C? 如何检查字符串是否仅包含字母数字字符和短划线? - How do I check if a string only contains alphanumeric characters and dashes? Java 编程:检查输入字符串是否为字母数字以及输入字符串中是否包含用户名前缀的 2 种方法 - Java Programing: 2 methods to check if an input string is alphanumeric and if the input string has a prefix of the user's name in it PHP增量字母数字字符串 - PHP Increment alphanumeric string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM