You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NSPredicate搭配正则验证用户名返回错误结果求助

Hey there! The issue here is actually pretty straightforward—you're including regex literal delimiters (/) in your pattern string, which NSPredicate doesn't expect. Let me break this down for you:

When you write regex in languages like JavaScript or Perl, you wrap the pattern in / to denote a regex literal. But NSPredicate's MATCHES operator expects a raw regex pattern string without those surrounding slashes. Your original pattern "/^[a-zA-Z0-9\\._]+$/" is telling the regex engine to match strings that start with a /, followed by your allowed characters, and end with another /—which your username ilikecode doesn't have, hence the false result.

Also, that \\. in your pattern is unnecessary. Inside a regex character set ([]), the dot . loses its special "match any character" meaning, so you can write it directly without escaping it.

Here's the fixed version of your code:

let username = "ilikecode"
let regexPattern = "^[a-zA-Z0-9._]+$"
let usernameTest = NSPredicate(format: "SELF MATCHES %@", regexPattern)
print("username is valid", usernameTest.evaluate(with: username), username)

This will correctly return true for your username, since it now checks for strings that consist entirely of uppercase/lowercase letters, numbers, dots, and underscores—exactly what you intended. As a quick check, if you test a username with invalid characters (like ilike-code or ilike@code), this will return false as expected.

内容的提问来源于stack exchange,提问作者ilikecode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:58:57