如何使用带标点符号的 NSStringEnumerationOptions.ByWords

How to use NSStringEnumerationOptions.ByWords with punctuation

我正在使用此代码查找 NSTextField 的字符串内容的 NSRange 和文本内容。

    nstext.enumerateSubstringsInRange(NSMakeRange(0, nstext.length),
        options: NSStringEnumerationOptions.ByWords, usingBlock: {
            (substring, substringRange, _, _) -> () in
            //Do something with substring and substringRange
    }

问题是 NSStringEnumerationOptions.ByWords 忽略了标点符号,所以

Stop clubbing, baby seals

变成

"Stop" "clubbing" "baby" "seals"

没有

"Stop" "clubbing," "baby" "seals

如果一切都失败了,我可以只检查给定单词之前或之后的字符,看看它们是否在豁免列表中(我在哪里可以找到哪些字符 .ByWords 豁免?);但必须有一个更优雅的解决方案。

如何从包含标点符号的字符串中找到一组单词的 NSRanges?

您可以改用 componentsSeparatedByString

var arr = nstext.componentsSeparatedByString(" ")

输出:

"Stop""clubbing,""baby""海豹

受 Richa 回答的启发,我使用了 componentsSeparatedByString(" ")。我必须添加一些代码才能使它对我有用,因为我想从输出中获取 NSRanges。如果同一个词有两个实例,我也希望它仍然有效——例如'please please stop clubbing, baby seals'。

这是我所做的:

            var words:  [String]    = []
            var ranges: [NSRange]   = []

            //nstext is a String I converted to a NSString
            words  = nstext.componentsSeparatedByString(" ")

            //apologies for the poor naming
            var nstextLessWordsWeHaveRangesFor = nstext

            for word in words
            {
                let range:NSRange = nstextLessWordsWeHaveRangesFor.rangeOfString(word)
                ranges.append(range)

                //create a string the same length as word so that the 'ranges' don't change in the future (if I just replace it with "" then the future ranges will be wrong after removing the substring)
                var fillerString:String = ""

                for var i=0;i<word.characters.count;++i{
                   fillerString = fillerString.stringByAppendingString(" ")
                }

                nstextLessWordsWeHaveRangesFor = nstextLessWordsWeHaveRangesFor.stringByReplacingCharactersInRange(range, withString: fillerString)
            }