我怎样才能在任何特殊字符之前添加额外的空格
how can i add extra spaces before any special character
如何在字符串中的任何特殊字符之前添加额外的空格,在 Swift 中,例如,如果我有字符串
var str = "#Whosebug@is$awesome"
" #Whosebug @is $awesome" // i have to achieve this...add empty spaces before every #
我们如何在Swift
中解决和实现这个
您可以使用正则表达式来匹配任何特殊字符 "[^\w]"
,这意味着任何非单词字符,并替换为相同的匹配项 "[=13=]"
,前面加上空格。如果您想排除空格被替换,您可以使用 "[^\w|\s]"
:
let str = "#Whosebug#is#awesome"
let result = str.replacingOccurrences(of: "[^\w]",
with: " [=10=]",
options: .regularExpression)
print(result) // " #Whosebug #is #awesome\n"
let str2 = "•Whosebug•is•awesome"
let result2 = str2.replacingOccurrences(of: "[^\w]",
with: " [=11=]",
options: .regularExpression)
print(result2) // " •Whosebug •is •awesome\n"
如何在字符串中的任何特殊字符之前添加额外的空格,在 Swift 中,例如,如果我有字符串
var str = "#Whosebug@is$awesome"
" #Whosebug @is $awesome" // i have to achieve this...add empty spaces before every #
我们如何在Swift
中解决和实现这个您可以使用正则表达式来匹配任何特殊字符 "[^\w]"
,这意味着任何非单词字符,并替换为相同的匹配项 "[=13=]"
,前面加上空格。如果您想排除空格被替换,您可以使用 "[^\w|\s]"
:
let str = "#Whosebug#is#awesome"
let result = str.replacingOccurrences(of: "[^\w]",
with: " [=10=]",
options: .regularExpression)
print(result) // " #Whosebug #is #awesome\n"
let str2 = "•Whosebug•is•awesome"
let result2 = str2.replacingOccurrences(of: "[^\w]",
with: " [=11=]",
options: .regularExpression)
print(result2) // " •Whosebug •is •awesome\n"