I am attempting to use regular expression to replace all occurrences of UK car registrations within a string.
The following swift code works perfectly for a when the string matches the regex exactly as below.
var myString = "DD11 AAA" var stringlength = countElements(myString) var ierror: NSError? var regex:NSRegularExpression = NSRegularExpression(pattern: "^([A-HK-PRSVWY][A-HJ-PR-Y])\\s?([0][2-9]|[1-9][0-9])\\s?[A-HJ-PR-Z]{3}$", options: NSRegularExpressionOptions.CaseInsensitive, error: &ierror)! var modString = regex.stringByReplacingMatchesInString(myString, options: nil, range: NSMakeRange(0, stringlength), withTemplate: "XX") print(modString)
The result is XX
However, the following does not work and the string is not modifed
var myString = "my car reg 1 - DD11 AAA my car reg 2 - AA22 BBB" var stringlength = countElements(myString) var ierror: NSError? var regex:NSRegularExpression = NSRegularExpression(pattern: "^([A-HK-PRSVWY][A-HJ-PR-Y])\\s?([0][2-9]|[1-9][0-9])\\s?[A-HJ-PR-Z]{3}$", options: NSRegularExpressionOptions.CaseInsensitive, error: &ierror)! var modString = regex.stringByReplacingMatchesInString(myString, options: nil, range: NSMakeRange(0, stringlength), withTemplate: "XX") print(modString)
The result is my car reg 1 - DD11 AAA my car reg 2 - AA22 BBB
Can anyone give me any pointers?
Swift String – Remove Specific Characters To remove specific set of characters from a String in Swift, take these characters to be removed in a set, and call the removeAll(where:) method on this string str , with the predicate that if the specific characters contain this character in the String.
Any string data can be replaced with another string in Python by using the replace() method. But if you want to replace any part of the string by matching a specific pattern then you have to use a regular expression.
You need to remove the ^
and $
anchors.
The ^
means start of string and $
means end of string (or line, depending on the options). That's why your first example works: in the first test string, the start of the string is really followed by your pattern and ends with it.
In the second test string, the pattern is found in the middle of the string, thus the ^...
can't apply. If you would just remove the ^
, the $
would apply on the second occurrence of the registration number and the output would be my car reg 1 - DD11 AAA my car reg 2 - XX
.
let myString = "my car reg 1 - DD11 AAA my car reg 2 - AA22 BBB" let regex = try! NSRegularExpression(pattern: "([A-HK-PRSVWY][A-HJ-PR-Y])\\s?([0][2-9]|[1-9][0-9])\\s?[A-HJ-PR-Z]{3}", options: NSRegularExpression.Options.caseInsensitive) let range = NSMakeRange(0, myString.count) let modString = regex.stringByReplacingMatches(in: myString, options: [], range: range, withTemplate: "XX") print(modString) // Output: "my car reg 1 - XX my car reg 2 - XX"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With