简体   繁体   English

如何在任何特殊字符之前添加额外的空格

[英]how can i add extra spaces before any special character

how to add extra spaces before any Special character in string,in Swift, for example if i have string如何在 Swift 中的字符串中的任何特殊字符之前添加额外的空格,例如,如果我有字符串

var str = "#StackOverFlow@is$awesome"

 " #StackOverFlow  @is  $awesome"   // i have to achieve this...add empty spaces before every # 

how can we solve and achieve this in Swift我们如何在 Swift 中解决并实现这一点

You can use a regular expression to match any special character "[^\\w]" which means any non word character and replace by the same match "$0" preceded by white spaces.您可以使用正则表达式匹配任何特殊字符"[^\\w]" ,这意味着任何非单词字符,并替换为前面带有空格的相同匹配"$0" If you would like to exclude whitespaces from being replaced you can use "[^\\w|\\s]" :如果您想排除空格被替换,您可以使用"[^\\w|\\s]"

let str =  "#StackOverFlow#is#awesome"
let result = str.replacingOccurrences(of: "[^\\w]",
                          with: "   $0",
                          options: .regularExpression)


print(result)  // "   #StackOverFlow   #is   #awesome\n"

let str2 =  "•StackOverFlow•is•awesome"
let result2 = str2.replacingOccurrences(of: "[^\\w]",
                          with: "   $0",
                          options: .regularExpression)


print(result2)  // "   •StackOverFlow   •is   •awesome\n"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM