Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying match String patterns in Swift. In my case related to time,
Example
"in 1 week"
"in 4 weeks"
I want to match the whole expression but return especially the number (Int) used between "in" and "week".
What's an efficient way to do this kind of string/pattern matching?
I did use e.g. rangeOfString for simple string matching before but I wonder how to tackle matching these more complex string patterns including its variable part.
Try this:
var pattern = "in\\s+(\\d+)\\s+weeks"
var error: NSError?
var regExp = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &error)!
func getWeekCount(input: String) -> String? {
let m = regExp.matchesInString(input, options: nil, range:NSMakeRange(0, countElements(input)))
print(m)
if let mm = m as? [NSTextCheckingResult] {
print(mm.count)
if mm.count >= 1 {
let range = m[0].rangeAtIndex(1)
return NSString(string: input).substringWithRange(range)
}
}
else {
print("no match")
}
return nil
}
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I have a String, lets say
var abc : String = "aaaabbbbbbbccddd"
I need an algorithm on how to change these repeating letters to the number of repeating letters (if there is more than 2 in a row), so that the given string would become
abc = "a4b7ccd3"
Any hint would be appreciated.
Let's start with this string :
let abc : String = "aaaabbbbbbbccddde"
And have the output in a new variable
var result = ""
Let's use an index to go through the characters in the string
var index = abc.startIndex
while index < abc.endIndex {
//There is already one character :
let char = abc[index]
var count = 0
//Let's check the following characters, if any
repeat {
count += 1
index = abc.index(after: index)
} while index < abc.endIndex && abc[index] == char
//and update the result accordingly
result += count < 3 ?
String(repeating: char, count: count) :
String(char) + String(count)
}
And here is the result :
print(result) //a4b7ccd3e
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have some variables all coming true just tarih1 output shows
Optional(2016). I didn't resolve it. I want to fix it to 2016.
My code below.
if let myString: String = String(seans.SeanceDate) {
let myStringArrf = myString.componentsSeparatedByString("T")
let tarih: NSString = myStringArrf[0]
let saat: String = String(myStringArrf[1])
let myStringArrf2 = saat.componentsSeparatedByString(":")
let saat1: String = myStringArrf2[0]
let saat2: String = myStringArrf2[1]
cell.saat.text = "\(saat1):\(saat2)"
cell.saat2.text = "\(saat1):\(saat2)"
let myStringArrf23 = tarih.componentsSeparatedByString("-")
let tarih1: NSString = myStringArrf23[0]
let tarih2: NSString = myStringArrf23[1]
let tarih3: NSString = myStringArrf23[2]
let sontarih: String = ("\(tarih3)-\(tarih2)-\(tarih1)")
cell.tarih.text = sontarih
print(sontarih)
}
You use optional binding to find out whether an optional contains a value, and if so, to make that
value available as a temporary constant or variable. Optional binding can be used with if and while
statements to check for a value inside an optional, and to extract that value into a constant or variable,
as part of a single action
if let constantName = someOptional {
// statements
}
if let tarih1 = myStringArrf23[0]{
print(tarih1)
}
This question already has answers here:
Detect whole word in NSStrings
(4 answers)
Closed 6 years ago.
What I want to do is to check if an entire word is present in a string. Let me give you an example.
let mainString = "this is a my string"
let searchString = "str"
if mainString.containsString(searchString) {
}
Here this condition will be true but I do not want this. I want it to be true when either "this" or "is" or "a" or "my" or "string" is searched in the mainString meaning I want to compare the whole word not the characters within the string. I hope I have elaborated it.
// The following method will return a string without punctuation and non-required stuff characters
Source of information : How to remove special characters from string in Swift 2?
func removeSpecialCharsFromString(mainString) -> String {
let okayChars : Set<Character> =
Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ".characters)
return String(text.characters.filter {okayChars.contains($0) })
}
let stringWithoutSpecialChars = removeSpecialCharsFromString(mainString)
// Source of info : Chris's answer on this page
let components = stringWithoutSpecialChars.componentsSeparatedByString(" ")
for component in components {
print(component)
}
You have to use a Regex like that :
NSString *pattern = #"\\str\\b";
NSRange range = [text rangeOfString:pattern options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
The \b at the end of the pattern do what you want, it will match only whole words.
I would recommend splitting your string into components and seeing if a component matches your string. Below is a method that uses components to check if any word matches a given search term.
func isTermInString(term:String, stringToSearch:String) -> Bool {
let components = stringToSearch.componentsSeparatedByString(" ")
for component in components {
if component == term {
return true
}
}
return false
}
This question already has answers here:
Formatting a UITextField for credit card input like (xxxx xxxx xxxx xxxx)
(30 answers)
Closed 6 years ago.
I've been stuck on this for awhile now and I was wondering what is the best way to format a textfield for a credit card type format?
You can use Caishen framework.
It updates the contents of the textfield after every edit using this function :
public func formattedCardNumber(cardNumberString: String) -> String {
let regex: NSRegularExpression
let cardType = cardTypeRegister.cardTypeForNumber(Number(rawValue: cardNumberString))
do {
let groups = cardType.numberGrouping
var pattern = ""
var first = true
for group in groups {
pattern += "(\\d{1,\(group)})"
if !first {
pattern += "?"
}
first = false
}
regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions())
} catch {
fatalError("Error when creating regular expression: \(error)")
}
return NSArray(array: self.splitString(cardNumberString, withRegex: regex)).componentsJoinedByString(self.separator)
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
What it the most common situation where you would want to return a function from a function in Swift?
In the code below I'm returning a function but I don't really see the purpose since the function I'm returning is inside the function who is returning it. The reason I'm confused is because we could accomplish the same thing with just one function.
func person () -> ((String, Int) -> String) {
func info(name: String, age: Int) -> (String) {
return "\(name) is \(age) old"
}
return info
}
let nathan = person()
nathan("Nathan", 3)
print(nathan("Nathan", 3))
Can someone point out common situations where you would want to return a function and probably illustrate it with a better example?
I want to understand this since this is fundamental for programming in general not just Swift (I think).
A classic example would be in a calculator program, e.g.:
func operatorForString(str: String) -> ((Float, Float) -> Float)? {
if str == "+" {
return (+) // brackets required to clarify that we mean the function
} else if str == "-" {
return (-)
} else if str == "*" {
return (*)
} else if str == "/" {
return (/)
} else if str == "**" {
return pow // No brackets required here
} else {
return nil
}
}
if let op = operatorForString("-") {
let result = op(1, 2) // -1
}
It's rather contrived, but it illustrates the principle simply...
As an "exercise to the reader" try to do it as a Dictionary lookup, rather than repeated ifs :)