JavaScript 不可用。

我们检测到浏览器禁用了 JavaScript。请启用 JavaScript 或改用支持的浏览器来继续访问

Solidity 智能合约模拟正则判断a-z0-9和连字符-

作者:Anban Chu

发表日期:2021年08月16日

所属目录:合约开发

场景描述

需要对字符串做限制,只能使用 a 至 z,0 至 9 和连字符-。因为 solidity 内没有正则表达式,所以只能逐个判断。

代码如下

pragma solidity ^0.8;

/// @notice Validates that a domain name is composed only from characters in the allowed character set:
/// - the lowercase letters `a-z`
/// - the digits `0-9`
/// - the hyphen `-`
/// @dev This function allows empty (zero-length) domains. If this should not be allowed, 
///     make sure to add a respective check when using this function in your code.
/// @param domain The name.
/// @return `true` if the name is valid or `false` if at least one char is invalid.
/// @dev Aborts on the first invalid char found.
function isDdomainValid(string calldata domain) pure returns (bool) {
    bytes calldata nameBytes = bytes(domain);
    uint256 nameLength = nameBytes.length;
    for (uint256 i; i < nameLength; i++) {
        uint8 char = uint8(nameBytes[i]);

        // if char is between a-z
        if (char > 96 && char < 123) {
            continue;
        }

        // if char is between 0-9
        if (char > 47 && char < 58) {
            continue;
        }

        // if char is -
        if (char == 45) {
            continue;
        }

        // invalid if one char doesn't work with the rules above
        return false;
    }
    return true;
}




以上就是本篇文章的全部内容了,希望对你有帮助。

>> 本站不提供评论服务,技术交流请在 Twitter 上找我 @anbang_account