[英]How can I check is there any consecutive characters with a regex in Swift 4.0?
Can anyone give me a Swift regex to identify consecutive characters in a string? 任何人都可以给我一个Swift正则表达式来识别字符串中的连续字符吗?
My regex is .*(.)\\\\1$
and this is not working. 我的正则表达式是
.*(.)\\\\1$
,这不起作用。 My code block is; 我的代码块是;
let regex = ".*(.)\\1$"
return NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: string)
Examples: 例子:
abc123abc -> should be valid
abc123abc - >应该有效
abc11qwe or aa12345 -> should not be valid because of
11
andaa
abc11qwe或aa12345 - >因
11
和aa
而无法生效
Thanks 谢谢
This regex may help you, (Identifies consecutive repeating characters - It validates and satisfies matches with samples you've shared. But you need to test other possible scenarios for input string.) 这个正则表达式可以帮助你,(标识连续的重复字符 - 它验证并满足与你共享的样本的匹配。但是你需要测试输入字符串的其他可能场景。)
(.)\\1
Try this and see: 试试看,看看:
let string = "aabc1123abc"
//let string = "abc123abc"
let regex = "(.)\\1"
if let range = string.range(of: regex, options: .regularExpression) {
print("range - \(range)")
}
// or
if string.range(of: regex, options: .regularExpression) != nil {
print("found consecutive characters")
}
Result: 结果:
Use NSRegularExpression
instead of NSPredicate
使用
NSRegularExpression
而不是NSPredicate
let arrayOfStrings = ["abc11qwe","asdfghjk"]
for string in arrayOfStrings {
var result = false
do{
let regex = try NSRegularExpression(pattern: "(.)\\1", options:[.dotMatchesLineSeparators]).firstMatch(in: string, range: NSMakeRange(0,string.utf16.count))
if((regex) != nil){
result = true
}
}
catch {
}
debugPrint(result)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.