How to replace occurences in string using groups in Swift? - ios

I simply need to replace:
<p>, <div>
with
\n<p>, \n<div>
in string with one single pattern replacing. Is it possible?
let string = "<p>hello</p> my <div>Doggy</div>"
let newString = string.replacingOccurrences(of: "<p>", with: "\n<p>").replacingOccurrences(of: "<div>", with: "\n<div>")
is there a better solution with regex?

You can do a regular expression search, with a template in the replacement
string:
let string = "<p>hello</p> my <div>Doggy</div>"
let newString = string.replacingOccurrences(of: "<p>|<div>", with: "\n$0", options: .regularExpression)
For each match, the $0 template is replaced by what actually matched the pattern.

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: "")

Cut a String from start position to end position with swift 3

I have Strings with the form string \ string example
"some sting with random length\233"
I want to deletes the last \ and get the value after it, so the result will be
"some sting with random length"
"233"
I tried this code but it's not working
let regex = try! NSRegularExpression(pattern: "\\\s*(\\S[^,]*)$")
if let match = regex.firstMatch(in: string, range: string.nsRange) {
let result = string.substring(with: match.rangeAt(1))
}
You did not correctly adapt the pattern from How to get substring after last occurrence of character in string: Swift IOS to your case. Both instances of the comma must be replaced by a backslash,
and that must be "double-escaped":
let regex = try! NSRegularExpression(pattern: "\\\\\\s*(\\S[^\\\\]*)$")
(once be interpreted as a literal backslash in the regex pattern, and
once more in the definition of a Swift string literal).
However, a simpler solution is to find the last occurrence of the
backslash and extract the suffix from that position:
let string = "some sting with random length\\233"
let separator = "\\" // A single(!) backslash
if let r = string.range(of: separator, options: .backwards) {
let prefix = string.substring(to: r.lowerBound)
let suffix = string.substring(from: r.upperBound)
print(prefix) // some sting with random length
print(suffix) // 233
}
Update for Swift 4:
if let r = string.range(of: separator, options: .backwards) {
let prefix = string[..<r.lowerBound]
let suffix = string[r.upperBound...]
print(prefix) // some sting with random length
print(suffix) // 233
}
prefix and suffix are a String.SubSequence, which can be used
in many places instead of a String. If necessary, create a real
string:
let prefix = String(string[..<r.lowerBound])
let suffix = String(string[r.upperBound...])
You could do this with regex, but I think this solution is better:
yourString.components(separatedBy: "\\").last!
It splits the string with \ as the separator and gets the last split.

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