Regex to not allow staring whitespace in string swift ios - ios

I want to create regex thats allows characters numbers and spaces but not at the begning of string , i have created below one but its not working "^\\S.*[^A-Za-z0-9_ ].*".
Swift:
func containsAllowedCharacters(regex: String?, stringToCheck: String) -> Bool {
var isValid = false
if let regex = regex {
let testString = NSPredicate(format: "SELF MATCHES %#", regex)
isValid = testString.evaluate(with: stringToCheck)
}
return !isValid
}

Your pattern, ^\S.*[^A-Za-z0-9_ ].*, matches start of string with ^, then matches any non-whitespace char with \S (note it matches any punctuation, letters and digits), then matches any zero or more chars other than line break chars as many as possbile with .*, then matches any char other than an ASCII letter, digit, _ or space, and then again matches any zero or more chars other than line break chars as many as possbile with .*.
As you see, all the pattern parts match more than you allow. Also, pay attention you actually require at least two chars to be present with this pattern while your code implies you need to support zero length string, too.
You can use
let FileNameRegex = #"^(?!\s)[A-Za-z0-9_\s]*$"#
NOTE: As you are using it with MATCHES in the NSPredicate.evaluate, you do not need the ^ and $ anchors on both ends since MATCHES requires a full string match:
let FileNameRegex = #"(?!\s)[A-Za-z0-9_\s]*"#
let testString = NSPredicate(format: "SELF MATCHES %#", regex)
Note the use of #"..."# notation that makes a raw string literal, where a single backslash is parsed as a literal backslash.
The pattern matches
^ - start of string
(?!\s) - a negative lookahead that matches a location in string that is not immediately followed with a whitespace
[A-Za-z0-9_\s]* - zero or more (due to the * quantifier) ASCII letters, digits, underscores and whitespaces
$ - end of string.

You are looking for lookaheads:
^(?! )[ \w]+$
\w is a short form for [\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}\u200c\u200d] (see here and here for more information) as it is used very often, but see #Wiktor's comment for a more precise clarification.
Also,see a demo on regex101.com.

Related

How to validate a name(John D'Largy) in iOS Swift4.2?

i tried all possibilities in stack-overflow (link1, link2) answers no use for me.
I am using following Regex to validate a first name. In online case (OnlineRegex) it is working fine but when i implemented in mobile it is not working.
Please help me
func isValidName() -> Bool {
let RegEx = "^[a-zA-Z]+(([\\'\\,\\.\\-\\ ][a-zA-Z ])?[a-zA-Z]*)*$"
let Test = NSPredicate(format:"SELF MATCHES %#", RegEx)
return Test.evaluate(with: self)
}
i am calling above function as
let str = "John D'Largy"
if str.isValidName(){
print("Valid")
}else{ print("Not valid")}
Output : "Valid"
Same function i am calling to validate my first text feild i am getting "Not valid"
if firstNameTxt.text.isValidName(){
print("Valid")
}else{ print("Not valid")}
i entered same text in mobile keyword
OutPut: "Not valid"
Did i missing something? or Should i have to change regex value?.
Any suggestions.
Thanks in Advance.
You may use
(?:[a-zA-Z]+(?:['‘’,.\\s-]?[a-zA-Z]+)*)?
The code you have already requires the full string match and you need no explicit anchors like ^ / \A and $ / \z.
Also, since the single quotation marks are automatically converted to curly quotes, you should either add them to the regex or turn off the behavior.
One of the most important things about thi regex is that it should be able to match partially correct string, thus all of the parts are optional (i.e. they can match 0 chars). It is wrapped with an optional non-capturing group ((?:...)?) that matches 1 or 0 occurrences.
Regex details
[a-zA-Z]+ - 1 or more letters
(?: - start of the inner non-capturing group:
['‘’,.\\s-]? - 1 or 0 whitespaces, single quotes, hyphens
[a-zA-Z]+ - 1+ letters
)* - 0 or more repetitions.
Note: to match any Unbicode letter, use \\p{L} instead of [a-zA-Z].
Graph:
See, I tried your code in the playground and changed the syntax a bit but not the logic
Below is the code snippet, try running that in your playground
func isValidName(str: String) -> Bool {
let RegEx = "^[a-zA-Z]+(([\\'\\,\\.\\-\\ ][a-zA-Z ])?[a-zA-Z]*)*$"
let Test = NSPredicate(format:"SELF MATCHES %#", RegEx)
return Test.evaluate(with: str)
}
func check(){
let str = "John D'Largy"
if isValidName(str: str){
print("Valid")
}else{
print("Not valid")
}
}
check()
Hope it helps!

How to implement a regex for password validation in Swift?

I want to implement a regex validaton for passwords in Swift? I have tried the following regex, but not successful
([(0-9)(A-Z)(!##$%ˆ&*+-=<>)]+)([a-z]*){6,15}
My requirement is as follows: Password must be more than 6 characters, with at least one capital, numeric or special character
You can use Regex for check your password strength
^(?=.*[A-Z].*[A-Z])(?=.*[!##$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$
Regex Explanation : -
^ Start anchor
(?=.*[A-Z].*[A-Z]) Ensure string has two uppercase letters.
(?=.*[!##$&*]) Ensure string has one special case letter.
(?=.*[0-9].*[0-9]) Ensure string has two digits.
(?=.*[a-z].*[a-z].*[a-z]) Ensure string has three lowercase letters.
.{8} Ensure string is of length 8.
$ End anchor.
Source - Rublar Link
try with this one for Password must be more than 6 characters, with at least one capital, numeric or special character
^.*(?=.{6,})(?=.*[A-Z])(?=.*[a-zA-Z])(?=.*\\d)|(?=.*[!#$%&? "]).*$
^ assert position at start of the string
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
(?=.{6,}) Positive Lookahead - Assert that the regex below can be matched
.{6,} matches any character (except newline)
Quantifier: {6,} Between 6 and unlimited times, as many times as possible, giving back as needed [greedy]
(?=.*[A-Z]) Positive Lookahead - Assert that the regex below can be matched
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[A-Z] match a single character present in the list below
A-Z a single character in the range between A and Z (case sensitive)
(?=.*[a-zA-Z]) Positive Lookahead - Assert that the regex below can be matched
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[a-zA-Z] match a single character present in the list below
a-z a single character in the range between a and z (case sensitive)
A-Z a single character in the range between A and Z (case sensitive)
(?=.*\\d) Positive Lookahead - Assert that the regex below can be matched
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
\d match a digit [0-9]
2nd Alternative: (?=.*[!#$%&? "]).*$
(?=.*[!#$%&? "]) Positive Lookahead - Assert that the regex below can be matched
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[!#$%&? "] match a single character present in the list below
!#$%&? " a single character in the list !#$%&? " literally (case sensitive)
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
$ assert position at end of the string
https://regex101.com/#javascript
more this you can try ....
Minimum 8 characters at least 1 Alphabet and 1 Number:
"^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"
Minimum 8 characters at least 1 Alphabet, 1 Number and 1 Special Character:
"^(?=.*[A-Za-z])(?=.*\\d)(?=.*[$#$!%*#?&])[A-Za-z\\d$#$!%*#?&]{8,}$"
Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet and 1 Number:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$"
Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[d$#$!%*?&#])[A-Za-z\\dd$#$!%*?&#]{8,}"
Minimum 8 and Maximum 10 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$#$!%*?&#])[A-Za-z\\d$#$!%*?&#]{8,10}"
public func isValidPassword() -> Bool {
let passwordRegex = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z!##$%^&*()\\-_=+{}|?>.<,:;~`’]{8,}$"
return NSPredicate(format: "SELF MATCHES %#", passwordRegex).evaluate(with: self)
}
If you need a quick fix. This is validation for a password with regex.
Copy/paste in helper or extension file and use it.
The regex is
(?:(?:(?=.*?[0-9])(?=.*?[-!##$%&*ˆ+=_])|(?:(?=.*?[0-9])|(?=.*?[A-Z])|(?=.*?[-!##$%&*ˆ+=_])))|(?=.*?[a-z])(?=.*?[0-9])(?=.*?[-!##$%&*ˆ+=_]))[A-Za-z0-9-!##$%&*ˆ+=_]{6,15}
func isValidPassword() -> Bool {
// least one uppercase,
// least one digit
// least one lowercase
// least one symbol
// min 8 characters total
let password = self.trimmingCharacters(in: CharacterSet.whitespaces)
let passwordRegx = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&<>*~:`-]).{8,}$"
let passwordCheck = NSPredicate(format: "SELF MATCHES %#",passwordRegx)
return passwordCheck.evaluate(with: password)
}
for which missing validation:
func getMissingValidation(str: String) -> [String] {
var errors: [String] = []
if(!NSPredicate(format:"SELF MATCHES %#", ".*[A-Z]+.*").evaluate(with: str)){
errors.append("least one uppercase")
}
if(!NSPredicate(format:"SELF MATCHES %#", ".*[0-9]+.*").evaluate(with: str)){
errors.append("least one digit")
}
if(!NSPredicate(format:"SELF MATCHES %#", ".*[!&^%$##()/]+.*").evaluate(with: str)){
errors.append("least one symbol")
}
if(!NSPredicate(format:"SELF MATCHES %#", ".*[a-z]+.*").evaluate(with: str)){
errors.append("least one lowercase")
}
if(str.count < 8){
errors.append("min 8 characters total")
}
return errors
}
func validpassword(mypassword : String) -> Bool
{
let passwordreg = ("(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z])(?=.*[##$%^&*]).{8,}")
let passwordtesting = NSPredicate(format: "SELF MATCHES %#", passwordreg)
return passwordtesting.evaluate(with: mypassword)
}
#IBOutlet weak var password_textfield: UITextField! //create a Password text field IBOutlet
#IBAction func login_btton(_ sender: UIButton) { //Click & Call to Login Button
let password = validpassword(mypassword: password_textfield.text!) //get text Field data & checked through the function
if(password == false)
{
print("Valid Password") //Use to Alert Msg Box
}
else
{
print("Login Safe") //Use to Alert Msg Box
}
}
## Function Use to validation is password and confirm password is same, Password must have more then some characters , Password contain some special character , Password must one digit , Password must one uppercase letter ##

swift ios alpha numeric regex that allows underscores and dashes

I am using this lib for validation and are trying to add my own regex.
What I want to do is to make a regex that allows alphanumeric A-Z 0-9 together with dashes and unserscores -_
I have tryed let regex = "[a-zA-Z0-9_-]" but I cant get it to work.
I also want the regex to not only allow english letters, but all languishes.
The lib works cause I have made another regex that only allows ints 0-9 which works
let intRegex = "^[0-9]*$"
Your regex look good but it will only match a single character. Do this "^[a-zA-Z0-9_-]*$" instead to match more than one character.
breakup --
^ -- start of string
[\pL0-9_-] -- characters you want to allow
* -- any number of characters (the crucial bit you were missing)
$ -- end of string
Building up on #charsi's answer
extension String {
var isAlphanumericDashUnderscore: Bool {
get {
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9_-]*$", options: .caseInsensitive)
return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
}
}
}

How modify the word boundary that includes '-' as a word character

I'd like to capture a passcode that is between 6 and 8 digits long.
I'd like to match:
123-4567 and
12-34-56-78
And fail:
1234567890 and 123-456-7890
As it stands I'm using (\\b(?:\\d[-,\\h]?+){5,7}\\d\\b)
This successfully knocks back 1234567890, but gives a partial match on 123-456-7890. Is there a way for the word boundary to include hyphens within it's count?
You can use lookarounds:
(?<!-)\b\d(?:[-,\h]?\d){5,7}(?!-)\b
See the regex demo
Swift regex uses ICU flavor, so both the lookbehind and a lookahead will work. The (?<!-) lookbehind makes sure there is no - before the digit that starts a new word (or after a word boundary), and (?!-) lookahead makes sure there is no - after the 8th digit right at the word boundary.
Do not forget to use double backslashes.
As #AlanMoore suggests, the word boundaries and --lookarounds can be substituted with lookarounds (?<![\w-]) and (?![\w-]). This will make the regex a bit more efficient since there will be only one position to be checked once at the start and end:
(?<![\w-])\d(?:[-,\h]?\d){5,7}(?![\w-])
See another demo
Not an exact literal answer, but an alternative native Swift solution
enum CheckResult {
case Success(String), Failure
}
func checkPassCode(string : String) -> CheckResult
{
let filteredArray = string.characters.filter{ $0 != "-" }.map{ String($0) }
return (6...8).contains(filteredArray.count) ? .Success(filteredArray.joinWithSeparator("")) : .Failure
}
checkPassCode("123-4567") // Success(1234567)
checkPassCode("12-34-56-78") // Success(12345678)
checkPassCode("1234567890") // Failure
checkPassCode("123-456-7890") // Failure

Swift - Regular Expression to match parentheses

I am trying to use regex to search through a string: "K1B92 (D) [56.094]" and I want to grab the "(D)" including the parentheses surrounding the "D". I am having trouble finding the correct expression to match the actual parentheses as simply putting parentheses will take it as a block and trying to escape the parentheses with "\" making it think its an expression to be evaluated. I also tried escaping "\(" with "\\(" as so: "\\([ABCD])\\)" but without luck. This is the code I have been using:
let str = "K1B92 (D) [56.094]"
let regex = NSRegularExpression(pattern: "\\b\\([ABCD])\\)\\b", options: NSRegularExpressionOptions.CaseInsensitive, error: nil)
let match = regex?.firstMatchInString(str, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0, count(str)))
let strRange = match?.range
let start = strRange?.location
let length = strRange?.length
let subStr = str.substringWithRange(Range<String.Index>(start: advance(str.startIndex, start!), end: advance(str.startIndex, start! + length!)))
// "\\b\([ABCD])\)\\b" returns range only for the letter "D" without parentheses.
// "\\b\\([ABCD])\\)\\b" returns nil
Can direct me towards the correct expression please? Thank you very much.
The \\([ABCD])\\) part is OK,
Correction: As #vacawama correctly said in his answer, the parentheses
do not match here. \\([ABCD]\\) matches one of the letters A-D
enclosed in parentheses.
The other problem is that there is no word boundary
(\b pattern) between a space and a parenthesis.
So you could either (depending on your needs), just remove the \b patterns, or replace them by \s for white space:
let regex = NSRegularExpression(pattern: "\\s\\([ABCD]\\)\\s", ...
But since the matched string should not include the space you need
a capture group:
let regex = NSRegularExpression(pattern: "\\s(\\([ABCD]\\))\\s", ...
// ...
let strRange = match?.rangeAtIndex(1)
The regular expression you need is "\\([ABCD]\\)". You need the double escape \\ before both open paren ( and close paren ).

Resources