Replacing Multiple Different Occurences with Multiple Different Replacements - Swift4.2

牧云@^-^@ 提交于 2020-12-21 04:03:54

问题


Trying to find the exact format for doing this.

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.

i.e. : replace "example" with "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) "

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.


回答1:


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


来源:https://stackoverflow.com/questions/64655945/replacing-multiple-different-occurences-with-multiple-different-replacements-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!