繁体   English   中英

使用regEx查找单词,然后使用Objective-c在两者之间添加空格

[英]Find words with regEx and then add whitespaces inbetween with Objective-c

我想知道如何使用Objective-C在字符串中的字母/数字之间添加空格。

我现在有样例代码正在工作。 基本上,我想将“ West4thStreet”变成“ West 4th Street”。

NSString *myText2 = @"West4thStreet"; 
NSString *regexString2 = @"([a-z.-][^a-z .-])"; 

for(NSString *match2 in [myText2 componentsMatchedByRegex:regexString2 capture:1L]) { 

    NSString *myString = [myText2 stringByReplacingOccurrencesOfString:match2 withString:@" "]; 
    NSLog(@"Prints out: %@",myString); // Prints out: Wes thStreet // Prints out: West4t treet   

}

因此,在此示例中,它将用空格替换我在regEx中找到的内容(“ t4”和“ hS”)。 但是我只想在字母之间添加一个空格以分隔单词。

谢谢!

如果将正则表达式模式的一部分用括号括起来,则可以在替换字符串中将它们称为$ 1,$ 2等(模式以左括号到右括号的顺序编号)。

NSString *origString = @"West4thStreet";
NSString *newString = [origString stringByReplacingOccurrencesOfRegex:@"(4th)" withString:@" $1 "];

不知道我能理解您的更广泛的用例,但这至少应该可以帮助您...

暂无
暂无

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

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