[英]How to check if a Regex is valid or not in Objective-C?
I got a Regex from an API. 我从API获得了正则表达式。 I need to validate the regex if it is valid or not.
我需要验证正则表达式是否有效。
This is a sample regex pattern: 这是一个示例正则表达式模式:
/^[a-z0-9_-]{6,18}$/
I need to validate this string. 我需要验证此字符串。
Edit: I have tried initwithpattern with a invalid regex [
, But its not throwing any error. 编辑:我已经尝试使用无效的regex
[
初始化initwithpattern ,但是它不会引发任何错误。
You should initialize an instance of NSRegularExpression
with the given regex pattern and check whether that NSRegularExpression
is NULL
. 您应该使用给定的regex模式初始化
NSRegularExpression
的实例,并检查NSRegularExpression
是否为NULL
。
NSString *regexString = @"/^[a-z0-9_-]{6,18}$/";
NSError *error = NULL;
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:regexString
options:0
error:&error];
if (!regex) {
//regex is invalid
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.