How to convert any textfield input to float in Swift - ios

I want to store float to CoreData and I want to convert every of the following inputs to 90.5:
90.5
90,5
90.5
90, 5
That means: Remove whitespace and convert , to .
Is this code best practice?
let str = " 90, 5 "
let converted = str.trimmingCharacters(in: .whitespacesAndNewlines)
let converted = strWithoutWithespace.replacingOccurrences(of: ",", with: ".")

No, it's not because it doesn't remove the space within the string.
The regex pattern "\\s+" removes all occurrences of one or more whitespace characters.
let str = " 90, 5 "
let strWithoutWhitespace = str.replacingOccurrences(of: "\\s+", with: "", options: .regularExpression)
let converted = strWithoutWhitespace.replacingOccurrences(of: ",", with: ".")

Related

Swift regex format to remove string contains brackets in iOS

Need to remove part of the string based on brackets.
For ex:
let str = "My Account (_1234)"
I wanted to remove inside brackets (_1234) and the result should be string My Account
Expected Output:
My Account
How can we achieve this with regex format or else using swift default class,need support on this.
Tried with separatedBy but it splits string into array but that is not the expected output.
str.components(separatedBy: "(")
Use replacingOccurrences(…)
let result = str.replacingOccurrences(of: #"\(.*\)"#,
with: "",
options: .regularExpression)
.trimmingCharacters(in: .whitespaces))
Regex ist not necessary. Just get the range of ( and extract the substring up to the lower bound of the range
let str = "My Account (_1234)"
if let range = str.range(of: " (") {
let account = String(str[..<range.lowerBound])
print(account)
}

replacingOccurrences(of: "'", with: "") Not Working On TextField.text

I get a input from uitextfield box. i can replace quotes("'") to empty(""). using
textfield.text.replacingOccurrences(of: "'", with: "")
is not working
textfield.text = "name's"
let trim = textfield.text?.replacingOccurrences(of: "'", with: "")
expected OUTPUT:
names
actual OUTPUT:
name's
text.replacingOccurrences can be used with regular expressions so using the group ['`´] could work here (I am not aware of any meta character for this). As #Rob mentioned in the comments it might be worth expanding the pattern further like [‘’'`´] or [‘’‛'′´`❛❜] or use "\p{Quotation_Mark}"
let trim = text.replacingOccurrences(of: "['`´]", with: "", options: .regularExpression)
It doesn't replace è or é which is good I suppose
let text = "name's are Josè and André, strings are `abc` and ´def´"
let trim = text.replacingOccurrences(of: "['`´]", with: "", options: .regularExpression)
print(trim)
yields
names are Josè and André, strings are abc and def

Convert string to URL by removing "\"

I want to remove the \" from the begining and the end of the particular string to get the actual URL
Code: let = subString = originalString.replacingOccurrences(of: "\", with: "")
"\"https://api.example.com/deep-link?url=some_url_encoded_string\""
What I want is:
"https://api.example.com/deep-link?url=some_url_encoded_string"
You could trim the string in order to remove all the leading and trailing quote symbols:
let url = "\"https://some-server/some/path\""
let processedString = str.trimmingCharacters(in: .init(charactersIn: "\""))
print(processedString) // https://some-server/some/path
Note that \" is not a string made of two characters, but an escape sequence for the quote symbol.
If you want to remove \" wherever it is occurred in the string then use this:
let subString = originalString.replacingOccurrences(of: "\"", with: "")
if you want to remove it just in the beginning and the end of the string then you will check:
if originalString.first == "\"" {
_ = originalString.removeFirst()
}
if originalString.last == "\"" {
_ = originalString.popLast()
}
You have to remove character ".
like that.
let myString = "\"https://api.example.com/deep-link?url=some_url_encoded_string\""
let newString = myString.replacingOccurrences(of: "\", with: "").replacingOccurrences(of: """, with: "")
print(newString)
Check below code
let originalString = "\"https://api.example.com/deep-link?url=some_url_encoded_string\""
var temp = "\("\"")" as? String
if originalString.hasPrefix(temp!){
originalString.replacingOccurrences(of: "\"", with: "")
}
This backslash is here just because you need double quotes in string which otherwise wouldn't be possible in string declared on one line in Swift 4.2 or earlier.
In Swift 5 you could use raw string literals
let originalString = #""https...""#
So you actually need to remove just the only characters which are actually in string and they're double quotes (simplified: \" = ").
To do this you have to again use backslash before double quote "\" -> "\""
let subString = originalString.replacingOccurrences(of: "\"", with: "")

Remove whitespace and multiple line from string?

I have a string , like this:
" \n assddd\n\n\n\n\n adjf fff dd \n\n\n\n tjhfhdf \n "
I want the result is:
"assddd\nadjffffdd\ntjhfhdf".
1: I used trimmingCharacters to remove the beginning and the ending:
let title = " \n assddd\n\n\n\n\n adjf fff dd \n\n\n\n tjhfhdf \n".trimmingCharacters(in: .whitespacesAndNewlines)
2: remove whitespaces
let result = title.replacingOccurrences(of: " ", with: "")
but, how to keep the first "\n" between the character and remove other "\n" ?
You can find two or more consecutive newline characters with
a regular expression, and replace them with a single newline
character. Example:
let s1 = "AA\n\nBB\nCC\n\n\n\n\nDD"
let s2 = s1.replacingOccurrences(of: "\\n{2,}", with: "\n", options: .regularExpression)
print(s1.debugDescription) // "AA\n\nBB\nCC\n\n\n\n\nDD"
print(s2.debugDescription) // "AA\nBB\nCC\nDD"
Applied to your case:
let title = " \n assddd\n\n\n\n\n adjf fff dd \n\n\n\n tjhfhdf \n "
let result = title.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: " ", with: "")
.replacingOccurrences(of: "\\n{2,}", with: "\n", options: .regularExpression)
print(result.debugDescription) // "assddd\nadjffffdd\ntjhfhdf"
Starting with your sample text, we can trim the ends:
let sample = " \n assddd\n\n\n\n\n adjf fff dd \n\n\n\n tjhfhdf \n "
let trimmedEnds = sample.trimmingCharacters(in: .whitespacesAndNewlines)
If you just want to remove space and compress newlines:
let noHorizSpace = trimmedEnds.replacingOccurrences(of: " ", with: "") // remove all spaces
let singleVertSpace = noHorizSpace.replacingOccurrences(of: "\\n{2,}", with: "\n", options: .regularExpression) // squash runs of two or more newlines
or using a regular expression for the spaces:
let noHorizSpace = trimmedEnds.replacingOccurrences(of: " +", with: "", options: .regularExpression)
let singleVertSpace = noHorizSpace.replacingOccurrences(of: "\\n{2,}", with: "\n", options: .regularExpression)
But (for fun?) what about all Unicode horizontal (spaces, tabs, etc.) and vertical (newlines, form feeds, paragraph separators, etc.)? For that there are the RE patterns \h and \v:
let noHorizSpace = trimmedEnds.replacingOccurrences(of: "\\h+", with: "", options: .regularExpression)
let singleVertSpace = noHorizSpace.replacingOccurrences(of: "\\v+", with: "\n", options: .regularExpression)
You can solve this with a single regular expression, but it is better to heed the advice in ICU RE User Guide and use multiple simpler REs.
A possible solution:
let str = " \n assddd\n\n\n\n\n adjf fff dd \n\n\n\n tjhfhdf \n "
print("str: \(str)")
let str2 = str.replacingOccurrences(of: " ", with: "")
print("str2: \(str2)")
let lines = str2.components(separatedBy:"\n")
print("lines: \(lines)")
let linesFiltered = lines.filter({($0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)).count > 0})
print("linesFiltered: \(linesFiltered)")
let linesTrimmed = linesFiltered.map({$0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)})
print("linesTrimmed: \(linesTrimmed)")
let endStr = linesTrimmed.joined(separator: "\n")
print("endStr:\n\(endStr)")
print("endStr:\n\(endStr.debugDescription)")
The idea:
Remove all spaces because you don't want them.
Get all lines separated by a breakLine ("\n") Because you need to reassemble them with only one if repeated and put them in an array
Remove empty lines (wether it's only spaces and/or new lines)
Remove space/newlines before and after each line (trim)
Recompose the string
This output:
str:
assddd
adjf fff dd
tjhfhdf
str2:
assddd
adjffffdd
tjhfhdf
lines: ["", "assddd", "", "", "", "", "adjffffdd", "", "", "", "tjhfhdf", ""]
linesFiltered: ["assddd", "adjffffdd", "tjhfhdf"]
linesTrimmed: ["assddd", "adjffffdd", "tjhfhdf"]
endStr:
assddd
adjffffdd
tjhfhdf
endStr:
"assddd\nadjffffdd\ntjhfhdf"
As I said in my comments using a regular expresion you can do this,
func stringByAdjustingString(text:String) ->String{
do{
let regex = try NSRegularExpression(pattern: "\\n+", options:[.dotMatchesLineSeparators])
let resultString = regex.stringByReplacingMatches(in: text, range: NSMakeRange(0, text.utf16.count), withTemplate: "\n")
return resultString.replacingOccurrences(of: " ", with: "").trimmingCharacters(in: .whitespacesAndNewlines)
}
catch{
return ""
}
}
input : " \n assddd\n\n\n\n\n adjf fff dd \n\n\n\n tjhfhdf \n "
Output : "assddd\nadjffffdd\ntjhfhdf"
It should help you
var str = " \n assddd\n\n\n\n\n adjf fff dd \n\n\n\n tjhfhdf \n "
str = str.trimmingCharacters(in: .whitespacesAndNewlines)
str = str.replacingOccurrences(of: " ", with: "")
//str = str.replacingOccurrences(of: "\n\n", with: "\n")
let array = str.components(separatedBy: "\n")
var finalArray = [String]()
for x in array {
if !x.isEmpty {
finalArray.append(x)
}
}
str = finalArray.joined(separator: "\n")
var titleTrimmedLines = [String]()
let title = " \n assddd\n\n\n\n\n adjf fff dd \n\n\n\n tjhfhdf \n "
title(separatedBy: CharacterSet.newlines).forEach { titleTrimmedLines.append($0.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)) }
let result = titleTrimmedLines.joined()
You can use for remove white spaces in string the following method
yourString.trimmingCharacters(in: .whitespaces)
or if you want delente white spaces and lines
yourString.trimmingCharacters(in: .whitespacesAndNewlines)
I hope it can be helpful!

Remove U\0000fffc unicode scalar from string

I receive an NSAttributedString that contains a NSTextAttachment. I want to remove that attachment, and it looks like it is represented as "\u{ef}" in the string. Printing the unicode scalars of such string, it also seems that unicode scalar for the "\u{ef}" is U\0000fffc.
I tried to do this:
noAttachmentsText = text.replacingOccurrences(of: "\u{ef}", with: "")
with no success, so I'm trying by comparing unicode scalars:
var scalars = Array(text.unicodeScalars)
for scalar in scalars {
// compare `scalar` to `U\0000fffc`
}
but I'm not able either to succeed in the comparison.
How could I do this?
But this code works for me from How do I remove "\U0000fffc" from a string in Swift?
let original = "First part \u{ef} Last part"
let originalRange = Range<String.Index>(start: original.startIndex, end: original.endIndex)
let target = original.stringByReplacingOccurrencesOfString("\u{ef}", withString: "", options: NSStringCompareOptions.LiteralSearch, range: originalRange)
print(target)
Output :
"First part ï Last part"
to
First part Last part
U can use similar code for swift 3 just replace unicode using replacingOccurrences option for exapmle :
func stringTocleanup(str: String) -> String {
var result = str
result = result.replacingOccurrences(of: "\"", with: "\"")
.replacingOccurrences(of: "\u{10}", with: "")
return result
}

Resources