This question already has an answer here:
Ignore escaped double quote characters swift
(1 answer)
Closed 6 years ago.
I define a string with:
static let Regex_studio_tel = "^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$"
But there comes an issue:
Invalid escape sequence in literal
The picture I token:
Edit -1
My requirement is match special plane numbers use Regex, such as:
My company have a special plane number:
028-65636688 or 85317778-8007
// aaa-bbbbbbbb-ccc we know the aaa is the prefix, and it means City Dialing Code, and bbbbbbbb is the main tel number, cccc is the landline telephone's extension number,
such as my company's landline telephone is 028-65636688, maybe our company have 10 extension number: 028-65636688-8007 ,028-65636688-8006,028-65636688-8005 and so on.
Of course, it maybe have a ext-number at the end.
028-65636688-2559
Two character sequence \ - is not a valid escape sequence in Swift String. When you need to pass \ - to NSRegularExpression as pattern, you need to write \\- in Swift String literal.
So, your line should be something like this:
static let Regex_studio_tel = "^(0[0-9]{2,3}\\-)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?$"
ADDITION
As Rob commented, minus sign is not a special character in regex when appearing outside of [ ], so you can write it as:
static let Regex_studio_tel = "^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$"
I'm guessing that your intent was to escape the - characters. But that's not necessary (and is incorrect). If your intent was to match just dashes, you should remove those backslashes entirely:
let pattern = "^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$"
Unrelated, but I'm suspicious of that + character. Did you really mean that you wanted to match one or more occurrences of [2-9][0-9]{6,7}? Or did you want to match exactly one occurrence?
Related
I have customer input that may include letters, digits or spaces. For instance:
local customer_input = 'I need 2 tomatoes';
or
local customer_input = 'I need two tomatoes';
However, due to the nature of my application, I may get #, *, #, etc, in the customer_input string. I want to remove any non alphanumeric characters but the space.
I tried with these:
customer_input , _ = customer_input:gsub("%W%S+", "");
This one drops everything but the first word in the phrase.
or
customer_input , _ = customer_input:gsub("%W%S", "");
This one actually drops the space and the first letter of each word.
So, I know I am doing it wrong but I am not really sure how to match alphanumeric + space. I am sure this must be simple but I have not been able to figure it out.
Thanks very much for any help!
You may use
customer_input , _ = customer_input:gsub("[^%w%s]+", "");
See the Lua demo online
Pattern details
[^ - start of a negated character class that matches any char but:
%w - an alphanumeric
%s - a whitespace
]+ - 1 or more times.
I've been trying to figure out the best way to validate a user entry which is a string with comma separated RGB values. It should only allow strings with no whitespaces and in formats such as these (1,12,123; 225,225,2; 32,42,241...).
I've never used Regex before, but i'm guessing it would be the best solution? I've been playing around on RegexPal and have gotten this string working:
(#([\da-f]{3}){1,2}(\d{1,3}%?,\s?){3}(1|0?\.\d+)\)|\d{1,3}%?(,\s?\d{1,3}%?){2})
However, not having much luck using it in Swift. I get the error "Invalid escape sequence in literal".
Would appreciate any help with using that regex in Swift, or if there's a better regex string/solution to validating the entry. Thanks!
You can use hashtag before the first double quote and after the last double quote in Swift to avoid having to manually add a backslash before any special character. Regarding the regex you are using it would allow the user to enter values above the 255 limit.
The regex below adapted from this post would limit the values from 0-255 and would allow the user enter 1 or more rgb values followed by ";" or "; "
#"^\((((([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])),){2}(([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]))(;|; )?){1,}\)$"#
extension StringProtocol {
var isValidRGB: Bool { range(of: #"^\((((([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])),){2}(([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]))(;|; )?){1,}\)$"#,
options: .regularExpression) != nil }
}
"(200,55,1)".isValidRGB // true
"(10,99,255; 0,0,10)".isValidRGB // true
"(2,2,2;)".isValidRGB // true
"(2,2,2;2)".isValidRGB // false
"(2,2,2;2,2)".isValidRGB // false
"(2,2,254;0,0,0)".isValidRGB // true
"(2,2,256;0,0,0)".isValidRGB // false
Add the Swift code where you define the RegEx to your question.
The other poster likely has identified the problem. (#manzarhaq, you should really post your reply as an answer so the OP can accept it.)
The backslash is a special character in Swift strings. It tells the compiler that the character next is a special character. If you want a literal backslash, you need 2 backslashes in a row. So your regEx string might look like this:
let regExStrin = "(#([\\da-f]{3}){1,2}(\\d{1,3}%?,\\s?){3}(1|0?\\.\\d+)\\)|\\d{1,3}%?(,\\s?\\d{1,3}%?){2})"
Note that using backslashes this way is common to most languages that derive, even loosely, from C. Swift does have some C in its ancestry.
In many C-like languages, \n is a newline character, \t is a tab character, \f is a form-feed, \" is a quotation mark, and \\ is a literal backslash.
(I don't think the \f form feed character is defined in Swift. That harks back to the days of ASCII driven serial printers.)
Hopefully a simple one,
I need a a limit of 8 numbers, the user need to write 8 number no more or less.
For now this is my code:
telefonRegex = "^(?=.*[0-9])$"
But it is not working, I just heard about regex fyi.
Your current regex never matches a string because it requires to start matching at the start of the string (^), then makes a forward check to require a digit ([0-9]) to appear after any 0+ chars other than line break chars (.*) and then tries to match the end of the string right after the beginning - tha is, it matches an empty string but also requires at least 1 digit in it.
You may just use
let telefonRegex = "^[0-9]{8}$"
or
let telefonRegex = "\\A[0-9]{8}\\z"
to match a string that only consists of 8 digits.
Details
^ - start of string (may be replaced by \\A in the string literal)
[0-9]{8} - exactly 8 occurrences of any digit
$ - end of string (to make sure the very end of string is matched, use \\z in the string literal).
Currently I have code that looks like this:
somestring = "param=valueZ&456"
local stringToPrint = (somestring):gsub("(param=)[^&]+", "%1hello", 1)
StringToPrint will look like this:
param=hello&456
I have replaced all of the characters before the & with the string "hello". This is where my question becomes a little strange and specific.
I want my string to appear as: param=helloZ&456. In other words, I want to preserve the character right before the & when replacing the string valueZ with hello to make it helloZ instead. How can this be done?
I suggest:
somestring:gsub("param=[^&]*([^&])", "param=hello%1", 1)
See the Lua demo
Here, the pattern matches:
param= - literal substring param=
[^&]* - 0 or more chars other than & as many as possible
([^&]) - Group 1 capturing a symbol other than & (here, backtracking will occur, as the previous pattern grabs all such chars other than & and then the engine will take a step back and place the last char from that chunk into Group 1).
There are probably other ways to do this, but here is one:
somestring = "param=valueZ&456"
local stringToPrint = (somestring):gsub("(param=).-([^&]&)", "%1hello%2", 1)
print(stringToPrint)
The thing here is that I match the shortest string that ends with a character that is not & and a character that is &. Then I add the two ending characters to the replaced part.
How to print all special characters without inserting escape sign before every of them? I have very large textiles with many special characters and I'm looking for something like # in c# which prints string literally as it is
What you're referring to, is called a verbatim string literal in C# and that concept does not translate exactly to Swift.
However, with the introduction of multiline string Literals in Swift 4, you can get close.
let multilineString = """
Here you can use \ and newline characters.
Also single " or double "" are allowed.
"""
For reference, find the grammar of a Swift String literal here.