1

I'm trying to search for a single plain quote mark (') in given String to then replace it with a single curved quote mark (’). I had tested more patterns but every time the search captures also the adjacent text. For example in the string "I'm", along with the ' mark it gets also the "I" and the "m".

(?:\\S)'(?:\\S)

Is there a possibility for achieve this or in the Swift implementation of Regex there is not support for non-capturing groups?

EDIT: Example

let startingString = "I'm"
let myPattern = "(?:\\S)(')(?:\\S)"
let mySubstitutionText = "’"

let result = (applyReg(startingString, pattern: myPattern, substitutionText: mySubstitutionText))

func applyReg(startingString: String, pattern: String, substitutionText: String) -> String {

    var newStr = startingString

    if let regex = try? NSRegularExpression(pattern: pattern, options: .CaseInsensitive) {
        let regStr = regex.stringByReplacingMatchesInString(startingString, options: .WithoutAnchoringBounds, range: NSMakeRange(0, startingString.characters.count), withTemplate: startingString)
        newStr = regStr
    }
    return newStr
}
1
  • Can't you just use lookarounds? let myPattern = "(?<=\\S)'(?=\\S)" Commented Jun 6, 2016 at 15:46

2 Answers 2

2

Matching but not capture a string in Swift Regex

In regex, you can use lookarounds to achieve this behavior:

let myPattern = "(?<=\\S)'(?=\\S)"

See the regex demo

Lookarounds do not consume the text they match, they just return true or false so that the regex engine could decide what to do with the currently matched text. If the condition is met, the regex pattern is evaluated further, and if not, the match is failed.

However, using capturing seems quite valid here, do not discard that approach.

Sign up to request clarification or add additional context in comments.

Comments

1

Put your quote in a capture group in itself

(?:\\S)(')(?:\\S)

For example, when matching against "I'm", this will capture ["I", "'", "m"]

4 Comments

Thank you. I added an example, are you so kind to tell me whether the implementation could be right? Maybe I'm missing something because the result is blank.
stringByReplacingMatchesInString will replace the whole match, including all capture groups. You can get around this by manually changing the string value of the range of the string containing the second capture group.
Or, you can change your substitution text to "$1’$3", this way the whole string is replaced, but the new string restores the first and third capture groups
Thank you so much AMomchilov!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.