2

I'm trying to build a regex that can look for names that contain apostrophes (O'Connor, O'Neil) and replace the apostrophes with 2 apostrophes (O''Connor, O''Neil).

I don't want to do this with all apostrophes in the string in question, just apostrophes that appear between two letters (upper or lower case). Now, I have no trouble finding instances of LETTER-APOSTROPHE-LETTER, but I'm not sure how to take that sequence and change the ' to ''.

5
  • 1
    I have a bad feeling about this... Commented Aug 10, 2012 at 14:59
  • 1
    @jnylen - Not very helpful, care to elaborate please?? Commented Aug 10, 2012 at 15:00
  • Are you trying to escape characters for a database query, or something similar? Commented Aug 10, 2012 at 15:01
  • Exactly, mySQL doesn't like single quotes Commented Aug 10, 2012 at 15:03
  • 2
    Don't do this - use the native methods for your DB that handle this exact situation, and many more that you haven't thought of. Commented Aug 10, 2012 at 15:04

4 Answers 4

7

You said this is for inserting values into a database. Don't do this - use parameterized queries instead, which will handle escaping properly. Jon Skeet says so.

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

1 Comment

Thanks! I'll look into this. I'm sure it will help in the future. Unfortunately, right now I don't have direct access to the DB insertion method as they are on the server. I'm processing strings and passing them to a web service. But in the end, yes, they do end up in the DB.
1
new Regex("([a-zA-Z])'([a-zA-Z])").Replace(input, match => match.Groups[1] + "''" + match.Groups[2])

3 Comments

This deletes the O and the C in O'Connor. I end up with ''onnor
Strange, new Regex("([a-zA-Z])'([a-zA-Z])").Replace("O'Connor", match => match.Groups[1] + "''" + match.Groups[2]) returns O''Connor to me..
My mistake, works fine! Just a little slip up on my end. Thank you very much!
1
string result = Regex.Replace(input, @"(?<=[^'])(')(?=[^'])", "''");

1 Comment

I prefer your method. It matches the apostrophe exactly using lookahead and lookbehind constructs, but I think you should replace the [^'] with [a-zA-Z] since it has to be a name, so no numbers or symbols.
0

This will work, I just tested it:

Regex.Replace("(\w)'(\w)","$1''$2");

(O'Connor, O'Neil) turns into (O''Connor, O''Neil)

1 Comment

Parameterized queries are definitely the better route, I'd go with that. This Regex solves your Regex question.

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.