用多个不同的替换替换多个不同的出现 - Swift4.2 [英] Replacing Multiple Different Occurences with Multiple Different Replacements - Swift4.2
问题描述
试图找到执行此操作的确切格式.
Trying to find the exact format for doing this.
我有一个 textField 用户输入,
I have a textField user input,
我想接受该输入并找到多次出现并分别用不同唯一字符替换每个唯一出现.
I want to take that input and find multiple occurrences and replace each unique occurrence with a different unique character respectively.
即:替换example
";带有1328571
"
这是我目前拥有的代码(目前只是为单个替换而设置,因此它不起作用),其格式可能有助于解释我要完成的任务:
This is my code I currently have (currently is just set up for a single replacement so it doesn't work), formatted in the way that might help to explain what I'm trying to accomplish:
let monoText: String = textInput.text!
let monoResult = monoText.replacingOccurrences(
of: ["e", "x", "a", "m", "p", "l", "e"],
with: ["1", "3", "2", "8", "5", "7"],
options: NSString.CompareOptions.literal, range:nil)
outputMono.text = " \(monoResult) "
我知道在其他语言(如 php)中执行此操作的方法:
I know of ways to do this in other langs like php:
$str = $post = 'Test $asd$ lol test asd $test$';
echo preg_replace('/\$(\w+)\$/','[bb]$1[/bb]',$str);
我可以去做一个非常长的替换集,但我想知道是否有什么东西可以帮助我而不是让我发疯.在别处找不到任何东西.
I could just go and do an extremely long replacement set but I wanted to know if there was SOMETHING that would assist me and not make me go insane. Couldn't find anything elsewhere.
推荐答案
我仍然不确定这是否正是您要问的问题,但如果我理解正确,您可以压缩您的集合并迭代生成的元组:
I am still not sure if this is exactly what you are asking but if I understood correctly you can zip your collections and iterate the resulting tuples:
var result = "example"
zip(["e", "x", "a", "m", "p", "l", "e"],["1", "3", "2", "8", "5", "7"]).forEach {
result = result.replacingOccurrences(of: $0, with: $1, options: .literal)
}
result // 1328571
这篇关于用多个不同的替换替换多个不同的出现 - Swift4.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!