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

时间:2021-08-19 04:57:23

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

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

3 个解决方案

#1


2  

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

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

import Foundation

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

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:

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

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

See the online Swift demo

查看在线Swift演示

Also, using NSPredicate with MATCHES is an alternative here:

此外,在这里使用NSPredicate和MATCHES是另一种选择:

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).

根据ICU v3,左手表达式使用正则表达式比较等于右手表达(有关详细信息,请参阅ICU用户指南中的正则表达式)。

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):

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

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

#2


5  

What you are looking for is range(of:options:range:locale:) then you can then compare the result of range(of:option:) with whole range of comparing string..

您正在寻找的是范围(of:options:range:locale :)然后您可以将范围(of:option :)的结果与整个比较字符串范围进行比较。

Example:

let phoneNumber = "(999) 555-1111"
let wholeRange = phoneNumber.startIndex..<phoneNumber.endIndex
if let match = phoneNumber.range(of: "\\(?\\d{3}\\)?\\s\\d{3}-\\d{4}", options: .regularExpression), wholeRange == match {
    print("Valid number")
}
else {
    print("Invalid number")
}
//Valid number

Edit: You can also use NSPredicate and compare your string with evaluate(with:) method of its.

编辑:你也可以使用NSPredicate并将你的字符串与它的evaluate(with :)方法进行比较。

let pattern = "^\\(?\\d{3}\\)?\\s\\d{3}-\\d{4}$"
let predicate = NSPredicate(format: "self MATCHES [c] %@", pattern)
if predicate.evaluate(with: "(888) 555-1111") {
    print("Valid")
}
else {
    print("Invalid")
}

#3


0  

Swift extract regex matches

Swift提取正则表达式匹配

with little bit of edit

一点点编辑

import Foundation

func matches(for regex: String, in text: String) -> Bool {
    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
        return !results.isEmpty
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return false
    }
}

Example usage from link above:

以上链接的示例用法:

let string = "19320"
let matched = matches(for: "^[1-9]\\d*$", in: string)
print(matched) // will match

let string = "a19320"
let matched = matches(for: "^[1-9]\\d*$", in: string)
print(matched) // will not match

#1


2  

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

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

import Foundation

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

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:

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

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

See the online Swift demo

查看在线Swift演示

Also, using NSPredicate with MATCHES is an alternative here:

此外,在这里使用NSPredicate和MATCHES是另一种选择:

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).

根据ICU v3,左手表达式使用正则表达式比较等于右手表达(有关详细信息,请参阅ICU用户指南中的正则表达式)。

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):

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

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

#2


5  

What you are looking for is range(of:options:range:locale:) then you can then compare the result of range(of:option:) with whole range of comparing string..

您正在寻找的是范围(of:options:range:locale :)然后您可以将范围(of:option :)的结果与整个比较字符串范围进行比较。

Example:

let phoneNumber = "(999) 555-1111"
let wholeRange = phoneNumber.startIndex..<phoneNumber.endIndex
if let match = phoneNumber.range(of: "\\(?\\d{3}\\)?\\s\\d{3}-\\d{4}", options: .regularExpression), wholeRange == match {
    print("Valid number")
}
else {
    print("Invalid number")
}
//Valid number

Edit: You can also use NSPredicate and compare your string with evaluate(with:) method of its.

编辑:你也可以使用NSPredicate并将你的字符串与它的evaluate(with :)方法进行比较。

let pattern = "^\\(?\\d{3}\\)?\\s\\d{3}-\\d{4}$"
let predicate = NSPredicate(format: "self MATCHES [c] %@", pattern)
if predicate.evaluate(with: "(888) 555-1111") {
    print("Valid")
}
else {
    print("Invalid")
}

#3


0  

Swift extract regex matches

Swift提取正则表达式匹配

with little bit of edit

一点点编辑

import Foundation

func matches(for regex: String, in text: String) -> Bool {
    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
        return !results.isEmpty
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return false
    }
}

Example usage from link above:

以上链接的示例用法:

let string = "19320"
let matched = matches(for: "^[1-9]\\d*$", in: string)
print(matched) // will match

let string = "a19320"
let matched = matches(for: "^[1-9]\\d*$", in: string)
print(matched) // will not match