使用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

