我有一个字符串:
Simple text with spaces
我需要一个正则表达式,可以选择以下内容:
- 开头有空格
- 结尾有空格
- 两个以上的空格
例如:
_ - space
_Simple text __with ___spaces_
我有一个字符串:
Simple text with spaces
我需要一个正则表达式,可以选择以下内容:
例如:
_ - space
_Simple text __with ___spaces_
let text = " Simple text with spaces "
let pattern = "^\\s+|\\s+$|\\s+(?=\\s)"
let trimmed = text.stringByReplacingOccurrencesOfString(pattern, withString: "", options: .RegularExpressionSearch)
println(">\(trimmed)<") // >Simple text with spaces<
^\s+
和\s+$
匹配字符串开头/结尾处的一个或多个空格字符。
棘手的部分是\s+(?=\s)
模式,它匹配一个或多个空格字符,后面紧跟着另一个空白字符,并且本身不被认为是匹配的一部分(即“前瞻断言”)。
通常情况下,\s
匹配所有空白字符,例如空格字符本身、水平制表符、换行符、回车符、换页符等。如果你只想删除(重复的)空格字符,则将该模式替换为
let pattern = "^ +| +$| +(?= )"
\s
匹配空格、制表符、换行符或进纸符。如果你只想匹配空格,请使用实际的空格。 - Robert Smit您可以将正则表达式简化,通过将前导/尾随部分作为第二阶段来完成:
let singlySpaced = " Simple text with spaces "
.stringByReplacingOccurrencesOfString("\\s+", withString: " ", options: .RegularExpressionSearch)
.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
^ | +| $
可以轻松地一次匹配前导/尾随/多个内容(正如 Robert 的答案所示)。棘手的部分是,如果您想要剥离,那么要用什么来替换它-您想用空白替换前导/尾随,但用单个空格替换多个内部空格。 - Airspeed Velocity+
表达式,选择单词之间的所有空格。我需要从第二个空格开始选择,一直到空格组的末尾。例如 word __word
。 - Artem Krachulovvar string : NSString = " hello world. "
while string.rangeOfString(" ").location != NSNotFound { //note the use of two spaces
string = string.stringByReplacingOccurrencesOfString(" ", withString: " ")
}
println(string)
string = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
println(string)
NSString *spaces =@"hi how are you ";
NSString *withoutSpace= [spaces stringByReplacingOccurrencesOfString:@" "
withString:@" "];
withoutSpace = [withoutSpace stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
此函数将在单词之间留下一个空格
let accountNameStr = " test test "
let trimmed = accountNameStr.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
let textWithoutSpace = trimmed.trimmingCharacters(in: .whitespaces)