Swift - Getting only AlphaNumeric Characters from String
You may directly use replacingOccurrences
(that removes all non-overlapping matches from the input string) with [^A-Za-z0-9]+
pattern:
let str = "_<$abc$>_"
let pattern = "[^A-Za-z0-9]+"
let result = str.replacingOccurrences(of: pattern, with: "", options: [.regularExpression])
print(result) // => abc
The [^A-Za-z0-9]+
pattern is a negated character class that matches any char but the ones defined in the class, one or more occurrences (due to +
quantifier).
See the regex demo.
Remove all non-numeric characters from a string in swift
I was hoping there would be something like stringFromCharactersInSet() which would allow me to specify only valid characters to keep.
You can either use trimmingCharacters
with the inverted
character set to remove characters from the start or the end of the string. In Swift 3 and later:
let result = string.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789.").inverted)
Or, if you want to remove non-numeric characters anywhere in the string (not just the start or end), you can filter
the characters
, e.g. in Swift 4.2.1:
let result = string.filter("0123456789.".contains)
Or, if you want to remove characters from a CharacterSet from anywhere in the string, use:
let result = String(string.unicodeScalars.filter(CharacterSet.whitespaces.inverted.contains))
Or, if you want to only match valid strings of a certain format (e.g. ####.##
), you could use regular expression. For example:
if let range = string.range(of: #"\d+(\.\d*)?"#, options: .regularExpression) {
let result = string[range] // or `String(string[range])` if you need `String`
}
The behavior of these different approaches differ slightly so it just depends on precisely what you're trying to do. Include or exclude the decimal point if you want decimal numbers, or just integers. There are lots of ways to accomplish this.
For older, Swift 2 syntax, see previous revision of this answer.
Check if a String is alphanumeric in Swift
extension String {
var isAlphanumeric: Bool {
return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
}
}
"".isAlphanumeric // false
"abc".isAlphanumeric // true
"123".isAlphanumeric // true
"ABC123".isAlphanumeric // true
"iOS 9".isAlphanumeric // false
Strip Non-Alphanumeric Characters from an NSString
We can do this by splitting and then joining. Requires OS X 10.5+ for the componentsSeparatedByCharactersInSet:
NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSString *strippedReplacement = [[someString componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];
Allow only alphanumeric characters for a UITextField
Use the UITextFieldDelegate method -textField:shouldChangeCharactersInRange:replacementString:
with an NSCharacterSet containing the inverse of the characters you want to allow. For example:
// in -init, -initWithNibName:bundle:, or similar
NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] invertedSet] retain];
- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}
// in -dealloc
[blockedCharacters release];
Note that you’ll need to declare that your class implements the protocol (i.e. @interface MyClass : SomeSuperclass <UITextFieldDelegate>
) and set the text field’s delegate
to the instance of your class.
Test UITextField text string to only contain alphanumeric characters
Check if the inversion of your accepted set is present:
if username.text!.rangeOfCharacterFromSet(letters.invertedSet) != nil {
print("invalid")
}
letters
should probably be alphanumericCharacterSet()
if you want to include numbers as well.
If you want to accept underscores or more chars, you will probably have to create a character set by your own. But the inversion logic will stay the same.
Swift: Regex for allowing alphanumeric with one mandatory numeral
You can limit the number of alphanumeric in a string using the pattern [a-zA-Z0-9]
and limit the minimum and maximum occurrences using {8,13}
. You can also make sure there is at least one digit doing a positive lookahead pattern for digits (?=.*\\d)
and non digits (?=.*\\D)
:
let regex = "^(?=.*\\d)(?=.*\\D)([a-zA-Z0-9]{8,13})$"
Regex details
^ asserts position at start of the string
(?=.*\d) • Positive lookahead that matches any character that's a
digit(?=.*\D) • Positive lookahead that matches any character thats a
non-digit([a-zA-Z0-9]) • First capturing group that matches any alphanumeric character
{8,13} • limits occurrences of the preciding token (from 8 to 13)
$ asserts position at end of the string
let string = "abcdefg1"
if let range = string.range(of: regex, options: .regularExpression) {
print(string[range]) // abcdefg1\n"
}
Allow only alpha numeric characters in UITextView
You can achieve that using [[[NSCharacterSet alphanumericCharacterSet] invertedSet]. This method will return a character set containing only characters that don’t exist in the receiver.
NSCharacterSet *charactersToBlock = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
//Conform UITextField delegate and implement this method.
- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
return ([characters rangeOfCharacterFromSet:charactersToBlock].location == NSNotFound);
}
Related Topics
Swift Sprite Kit in App Purchase
Xcode 11 - Disable Resize Mode in Catalyst Swift
Closure:Use Unresolved Identifier 'Self'
Ios8 Swift Uisearchcontroller Hides Navigationbar
How to Increase the Scope of Variables in Switch-Case/Loops in Swift
Swiftui Editbutton Action on Done
Xcode - Build Setting "Excluded_Source_File_Names" Not Working
How to Access Content View's Elements Later in Swiftui
Best Way to Structure My Firebase Database
What Is Darwinboolean Type in Swift
Swift Any Difference Between Closures and First-Class Functions
Create a Navigationlink Without Back Button Swiftui
Textfield in Swiftui Loses Focus When I Enter a Character
Class with Non-Optional Property Conforming to Protocol with Optional Property