NSRegularExpression does not match anything after CRLF. Why? - swift

In Swift 4.2, NSRegularExpression does not match anything after CRLF. Why?
let str = "\r\nfoo"
let regex = try! NSRegularExpression(pattern: "foo")
print(regex.firstMatch(in: str, range: NSRange(location: 0, length: str.count))) // => nil
If you remove "\r" or "\n", you get a instance of NSTextCheckingResult.

In Swift 4 a new initializer of NSRange was introduced to convert reliably Range<String.Index> to NSRange.
Use it always, it solves your issue.
let str = "\r\nfoo"
let regex = try! NSRegularExpression(pattern: "foo")
print(regex.firstMatch(in: str, range: NSRange(str.startIndex..., in: str)))

Related

regular expressions: simplified form?

I'm finally learning swift. The documentation that I've seen for regex in swift consist of something like the following:
let testString = "hat"
let range = NSRange(location: 0, length: testString.utf16.count)
let regex = try! NSRegularExpression(pattern: "[a-z]at")
let r = regex.firstMatch(in: testString, options: [], range: range) != nil
print("ns-based regex match?: ", r)
Is this the preferred/only way of doing this or is there an updated technique?
It's a bit verbose.
We’d often just use range(of:options:range:locale:) with a .regularExpression:
let testString = "foo hat"
if let range = testString.range(of: "[a-z]at", options: .regularExpression) {
print(testString[range])
}
If you don't need some of the more advanced NSRegularExpression options, the above is bit simpler.

Find multiple urls with regex

I need to find multiple urls within a string. The regex I'm using is
(https?:\/\/.*\.(?:png|jpg))
and the string is
Newhttps://www.findregexhere.com/newimage.pngfrhttps://www.findregexhere.com/newimage.pngnewimage
Here is the code I am using
let regex = try NSRegularExpression(pattern: "https?:\/\/.*\.(?:png|jpg)$", options: .caseInsensitive)
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
but the result is giving me this
https://www.findregexhere.com/newimage.pngfrhttps://www.findregexhere.com/newimage.png
Try non-greedy with...
(https?:\/\/.*?\.(?:png|jpg))
Demo: https://regex101.com/r/AK5foS/1

Remove occurrence of Unicode character \u{ef} from String In Swift 3

Remove occurrence of Unicode character \u{ef} from String In Swift 3.
Example String:- "\u{ef}\n \n\u{ef}\n 🍏\n\u{ef}"
Thanks In advance.
Use the replacingOccurrences on your String:
let str = "\u{ef}\n \n\u{ef}\n 🍏\n\u{ef}".trimmingCharacters(in: .whitespaces)
let newStr = str.replacingOccurrences(of: "\u{ef}", with: "", options: NSString.CompareOptions.literal, range:nil)
print(newStr) // 🍏

Remove a line of characters in a String with Swift

I read many questions about removing characters from a string. But none of them resolved my issue.
I have this string:
"\"iconCls\":X.net.RM.getIcon(\"BulletWhite\")"
I want to replace this part:
"X.net.RM.getIcon(\"BulletWhite\")"
By this (double quotes in fact):
"\"\""
I use this code:
let dataString = "\"iconCls\":X.net.RM.getIcon(\"BulletWhite\")"
let newString = dataString?.replacingOccurrences(of: "X.net.RM.getIcon(\"BulletWhite\")" as String, with: "", options: .regularExpression, range: nil)
But it doesn't work. I can replace all characters until I want to replace strings containing parentheses.Any idea? Thanks!
You are passing the .regularExpression option but you are not actually using a regular expression.
Change:
.regularExpression
to:
[]
This gives the result you want:
let dataString = "\"iconCls\":X.net.RM.getIcon(\"BulletWhite\")"
let newString = dataString.replacingOccurrences(of: "X.net.RM.getIcon(\"BulletWhite\")" as String, with: "", options: [], range: nil)
Output:
"icnCls":
Even simpler:
let newString = dataString.replacingOccurrences(of: "X.net.RM.getIcon(\"BulletWhite\")" as String, with: "")
You don't need to use options or range for this.
let str = "\"iconCls\":X.net.RM.getIcon(\"BulletWhite\")"
let replace = "X.net.RM.getIcon(\"BulletWhite\")"
let replaceBy = "\"\""
let newString = str.replacingOccurrences(of: replace, with: replaceBy)

How can I substring this string?

how can I substring the next 2 characters of a string after a certian character. For example I have a strings str1 = "12:34" and other like str2 = "12:345. I want to get the next 2 characters after : the colons.
I want a same code that will work for str1 and str2.
Swift's substring is complicated:
let str = "12:345"
if let range = str.range(of: ":") {
let startIndex = str.index(range.lowerBound, offsetBy: 1)
let endIndex = str.index(startIndex, offsetBy: 2)
print(str[startIndex..<endIndex])
}
It is very easy to use str.index() method as shown in #MikeHenderson's answer, but an alternative to that, without using that method is iterating through the string's characters and creating a new string for holding the first two characters after the ":", like so:
var string1="12:458676"
var nr=0
var newString=""
for c in string1.characters{
if nr>0{
newString+=String(c)
nr-=1
}
if c==":" {nr=2}
}
print(newString) // prints 45
Hope this helps!
A possible solution is Regular Expression,
The pattern checks for a colon followed by two digits and captures the two digits:
let string = "12:34"
let pattern = ":(\\d{2})"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
if let match = regex.firstMatch(in: string, range: NSRange(location: 0, length: string.characters.count)) {
print((string as NSString).substring(with: match.rangeAt(1)))
}