Arti
Arti

Reputation: 7762

Search and replace with “match words only” option

I need to replace all determiners from sentence. My problem that when i replace "a", it replace this letter in word.

str.stringByReplacingOccurrencesOfString("a", withString: "")

For example: a match a

The result will be: mtch

But i want: match

Upvotes: 1

Views: 53

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626920

You can detect whole words with \b word boundary, and also, you can grab optional whitespace after these words with \s* (1+ whitespace). Then, we can make sure no leading spaces are left with .stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).

Also note that strings in Swift are C strings (support escape sequences) and since the regex special metacharacters need to be escaped with a literal backslash, you need to actually double the backslashes in the pattern (i.e. \s -> "\\s").

Here is Swift 2.1 sample code:

var s = "a match a"
var out_s = ""
if let regex = try? NSRegularExpression(pattern: "\\ba\\b\\s*", options: .CaseInsensitive) {
    out_s = regex.stringByReplacingMatchesInString(s, options: .WithTransparentBounds, range: NSMakeRange(0, s.characters.count), withTemplate: "")
    print("\""+out_s.stringByTrimmingCharactersInSet(
        NSCharacterSet.whitespaceAndNewlineCharacterSet()
    )+"\"")
}

It prints "match".

Note also that options: .CaseInsensitive will perform a case insensitive match, use options: [] to make the search case sensitive.

Now, if you have a list of the determiners, use alternation:

"\\b(?:an?|the)\\b\\s*"

This expression will match a, an or the followed with 0+ whitespace.

Upvotes: 1

user2705585
user2705585

Reputation:

You should try with word boundaries like this /\ba\b/. Should use g global search and case insensitive i flags.

Word boundary \b makes sure that there is no character followed or preceded by a.

Regex101 Demo

Upvotes: 1

Related Questions