Swift Regular Expression Format

Swift regular expression format?

Within double quotes, a single backslash would be readed as an escape sequence. You need to escape all the backslashes one more time in-order to consider it as a regex backslash character.

"^([1-9]\\d{0,2}(,\\d{3})*|([1-9]\\d*))(\\.\\d{2})?$" 

Swift/Regex: How can I format a string using stringByReplacingMatches(withTemplate)?

You would need to change your regular expression to match one number at the start of the string or two numbers.

((^[0-9])|([0-9]{2}))(?!$)

Regular expressions in swift

Separate the string by non alpha numeric characters except white spaces. Then trim the elements with white spaces.

extension String {
func words() -> [String] {
return self.components(separatedBy: CharacterSet.alphanumerics.inverted.subtracting(.whitespaces))
.filter({ !$0.isEmpty })
.map({ $0.trimmingCharacters(in: .whitespaces) })
}
}

let string1 = "(name,john,string for user name)"
let string2 = "(name, john,name of john)"
let string3 = "key = value // comment"

print(string1.words())//["name", "john", "string for user name"]
print(string2.words())//["name", "john", "name of john"]
print(string3.words())//["key", "value", "comment"]

Regular expression in Swift not working fully

You can try this:

"^-?[0-9]{1,3}[.]{1}[0-9]{6}$"

With:

  • ^ : Start of a string
  • $ : End of a string

Here are some test cases:

let latitudes = ["?.-33.476543", 
"-33555.476543",
"-33.476543546565565765",
"abc-333.476543xyz",
"-333.476543",
]

let regex = NSRegularExpression("^-?[0-9]{1,3}[.]{1}[0-9]{6}$")

for latitude in latitudes {
print(regex.matches(latitude), "\t", latitude)
}

Here is the output:

false    ?.-33.476543
false -33555.476543
false -33.476543546565565765
false abc-333.476543xyz
true -333.476543

Regular expression to find a number ends with special character in Swift

You can use

func isValidItem(_ item: String) -> Bool {
let pattern = #"^[0-9]+\$\z"#
return (item.range(of: pattern, options: .regularExpression) != nil)
}

let arr = ["Foo", "Foo1", "Foo$", "$Foo", "1Foo", "1$", "20$", "1$Foo", "12$$"]

print(arr.filter {isValidItem($0)})
// => ["1$", "20$"]

Here,

  • ^ - matches start of a line
  • [0-9]+ - one or more ASCII digits (note that Swift regex engine is ICU and \d matches any Unicode digits in this flavor, so [0-9] is safer if you need to only match digits from the 0-9 range)
  • \$ - a $ char
  • \z - the very end of string.

See the online regex demo ($ is used instead of \z since the demo is run against a single multiline string, hence the use of the m flag at regex101.com).

Regular expression in Swift

In the pattern, you are making use of parts that are very broad matches.

For example, .+ will first match until the end of the line, [\\S ]* will match either a non whitespace char or a space and [^-]* matches any char except a -

The reason it could potentially break is that the broad matches first match until the end of the string. As a single : is mandatory in your pattern, it will backtrack from the end of the string until it can match a : followed by a whitespace, and then tries to match the rest of the pattern.

Adding another : in the message part, may cause the backtracking to stop earlier than you would expect making the message group shorter.


You could make the pattern a bit more precise, so that the last part can also contain : without breaking the groups.

 (\[[^][]*\])\s([^:]*):\s(.*)$
  • (\[[^][]*\]) Match the part from an opening till closing square bracket [...] in group 1
  • \s Match a whitespace char
  • ([^:]*): Match any char except : in group 2, then match the expected :
  • \s(.*) Match a whitespace char, and capture 0+ times any char in group 3
  • $ End of string

Regex demo

How do you write regular expressions for a valid username for swift?

^\w{1,13}$

^ beginning of string anchor

\w word character - any letter (including UTF-8), any case, 0-9 and underscore

{1,13} length between 1 and 13, inclusive

$ end of string anchor

https://regex101.com/ - good resource

Regular expression with backslash in swift

You can solve this by using a raw string for your regular expresion, that is a string surrounded with #

let pattern = #"(NAME\\)(.*)\s"# 

Note that name and the \ is in a separate group that can be referenced when replacing

let output = string.replacingOccurrences(of: pattern, with: "$1\(new_value) ", options: .regularExpression)

Swift regex: does a string match a pattern?

Swift version 3 solution:

if string.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil ...

Swift version 2 solution:

if string.rangeOfString(pattern, options: .RegularExpressionSearch) != nil ...

Example -- does this string contain two letter "o" characters?

"hello world".rangeOfString("o.*o", options: .RegularExpressionSearch) != nil

Note: If you get the error message 'String' does not have a member 'rangeOfString', then add this before: import Foundation. This is because
Foundation provides the NSString methods that are automatically bridged to the Swift String class.

import Foundation

Thanks to Onno Eberhard for the Swift 3 update.

Check string matches exact format swift 5

You need two things:

  • Escape parentheses
  • Add anchors because in the current code, the regex can match a part of a string.

You can thus use

stringToCheck.range(of: #"^\([0-9],[0-9]\)\z"#, options: .regularExpression, range: nil, locale: nil) != nil

Note the # chars on both ends, they allow escaping with single backslashes.

Details:

  • ^ - start of string
  • \( - a ( char
  • [0-9] - a single ASCII digit (add + after ] to match one or more digits)
  • , - a comma
  • [0-9] - a single ASCII digit (add + after ] to match one or more digits)
  • \) - a ) char
  • \z - the very end of string (if linebreaks cannot be present in the string, $ is enough).


Related Topics



Leave a reply



Submit