简体   繁体   中英

How can I replace the last word using Regex?

I have a String extension:

func replaceLastWordWithUsername(_ username: String) -> String {
    let pattern = "@*[A-Za-z0-9]*$"
    do {
        Log.info("Replacing", self, username) 
        let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
        let range = NSMakeRange(0, self.characters.count)
        return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: username )
    } catch {
        return self
    }
}

let oldString = "Hey jess"
let newString = oldString.replaceLastWordWithUsername("@jessica")

newString now equals Hey @jessica @jessica . The expected result should be Hey @jessica

Use this regex:

(?<=\s)\S+$

Sample: https://regex101.com/r/kGnQEM/1

/(?<=\\s)\\S+$/g

Positive Lookbehind (?<=\\s)

Assert that the Regex below matches

\\s matches any whitespace character (equal to [\\r\\n\\t\\f\\v ])

\\S+ matches any non-whitespace character (equal to [^\\r\\n\\t\\f ])

  • Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)

Just change your pattern:

let pattern = "\\w+$"
  • \\w matches any word character, ie [A-Za-z0-9]
  • + means one or more

I think it's because the * regex operator will

Match 0 or more times. Match as many times as possible.

This might be causing it to also match the 'no characters at the end' in addition to the word at the end, resulting in two replacements.

As mentioned by @Code Different, if you use let pattern = "\\\\w+$" instead, it will only match if there are characters, eliminating the 'no characters' match.

"Word1 Word2"
        ^some characters and then end
            ^0 characters and then end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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