确保正则表达式与 Swift 正则表达式匹配整个字符串

编程入门 行业动态 更新时间:2024-10-23 14:25:13
本文介绍了确保正则表达式与 Swift 正则表达式匹配整个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何检查一个 WHOLE 字符串是否可以匹配正则表达式?在 Java 中是方法 String.matches(regex)

How to check whether a WHOLE string can be matches to regex? In Java is method String.matches(regex)

推荐答案

你需要使用锚点,^(字符串锚点的开始)和$(字符串的结束)锚点),带有 range(of:options:range:locale:),传递.regularExpression 选项:

You need to use anchors, ^ (start of string anchor) and $ (end of string anchor), with range(of:options:range:locale:), passing the .regularExpression option:

import Foundation let phoneNumber = "123-456-789" let result = phoneNumber.range(of: "^\\d{3}-\\d{3}-\\d{3}$", options: .regularExpression) != nil print(result)

或者,您可以传递一组选项,[.regularExpression, .anchored],其中 .anchored 只会将模式锚定在字符串的开头,您可以省略 ^,但仍然需要 $ 锚定在字符串末尾:

Or, you may pass an array of options, [.regularExpression, .anchored], where .anchored will anchor the pattern at the start of the string only, and you will be able to omit ^, but still, $ will be required to anchor at the string end:

let result = phoneNumber.range(of: "\\d{3}-\\d{3}-\\d{3}$", options: [.regularExpression, .anchored]) != nil

查看在线 Swift 演示

此外,使用 NSPredicate 和 MATCHES 是这里的替代:

Also, using NSPredicate with MATCHES is an alternative here:

左手表达式等于右手表达式,根据 ICU v3 使用正则表达式样式比较(有关更多详细信息,请参阅 正则表达式).

The left hand expression equals the right hand expression using a regex-style comparison according to ICU v3 (for more details see the ICU User Guide for Regular Expressions).

MATCHES 实际上在字符串的开头和结尾都锚定了正则表达式匹配(注意这可能不适用于所有 Swift 3 版本):

MATCHES actually anchors the regex match both at the start and end of the string (note this might not work in all Swift 3 builds):

let pattern = "\\d{3}-\\d{3}-\\d{3}" let predicate = NSPredicate(format: "self MATCHES [c] %@", pattern) let result = predicate.evaluate(with: "123-456-789")

更多推荐

确保正则表达式与 Swift 正则表达式匹配整个字符串

本文发布于:2023-10-23 13:50:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521005.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正则表达式   字符串   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!