[英]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.