i want to make regex to only take number 0 in front of the sentence in swift

You can use the following regular expression to match only the numbers that start with 0 in a Swift string:

main.swift
let regex = try! NSRegularExpression(pattern: "^0\\d*", options: [])
69 chars
2 lines

Here, the ^ symbol matches the start of the string, 0 matches a literal '0', and \\d* matches zero or more digits.

You can use this regular expression to extract the matched numbers from a given string:

main.swift
let string = "01234 hello world 0456"
if let match = regex.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count)) {
    let matchedString = (string as NSString).substring(with: match.range)
    print(matchedString) // Outputs: "01234"
} else {
    print("No match found")
}
312 chars
8 lines

In the above code, we first define our regular expression and then use it to extract the matched string from a given input string. Here, string variable contains some random string containing a number starting with '0'. We then use the NSRegularExpression method firstMatch(in:options:range:) to get the first matching substring from the input string. If a match is found, we extract the matched substring and print it. Otherwise, we print "No match found".

gistlibby LogSnag