Swift仅从字符串中删除尾随空格 [英] Swift remove ONLY trailing spaces from string

查看:36
本文介绍了Swift仅从字符串中删除尾随空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SO 中的许多示例都固定两侧,前导和尾随.我的要求只是关于尾随.我的输入文本是:保持我的左侧"所需的输出:保持我的左侧"

many examples in SO are fixing both sides, the leading and trailing. My request is only about the trailing. My input text is: " keep my left side " Desired output: " keep my left side"

当然这个命令会去除两端:

Of course this command will remove both ends:

let cleansed = messageText.trimmingCharacters(in: .whitespacesAndNewlines)

这对我不起作用.

我该怎么做?

推荐答案

一个相当简单的解决方案是正则表达式,模式是一个或多个(+)空白字符(\s) 在字符串的末尾($)

A quite simple solution is regular expression, the pattern is one or more(+) whitespace characters(\s) at the end of the string($)

let string = " keep my left side "
let cleansed = string.replacingOccurrences(of: "\\s+$", 
                                         with: "", 
                                      options: .regularExpression)

这篇关于Swift仅从字符串中删除尾随空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆