LGAP
LGAP

Reputation: 2463

Regular Expression Needed For Single Quote Detection

I need a regular expression to find the single quotes in (Anand's & boy's) of the below scenario,

'This has to be Anand's first task', 'A boy's friend works in France'

Consider I have many fields to be inserted in to DB like what I have shown in the example above.

I have error with the queries which has a single quote in its text. I need to find them and replace with '' two single quotes for this to solve.

Can you help me in writing the regex for this purpose? As I do not have much insight on regEx.

Upvotes: 0

Views: 197

Answers (3)

David Soroko
David Soroko

Reputation: 9096

If this is a JDBC scenario, try using Prepared Statements . That is a much better approach then modifying the original data and as additional benefit protects you from SQL injection attacks.

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336398

You should rather be working on how to make sure that you don't get these obviously incorrect quotes in your input in the first place. But if you can't, you have a fighting chance by finding quotes that are not followed by a comma (or end of string) and are not preceded by a comma (or start of string):

String resultString = subjectString.replaceAll("(?<!^|, ?)'(?!,|$)", "''");

Upvotes: 2

vainolo
vainolo

Reputation: 6987

  1. split the text using the delimiter "," (String.split(","))
  2. trim each resulting string (String.trim())
  3. remove first and last characters of the resulting string (removing initial and final "'" (String.subsequence())
  4. replace "'" with """ (String.replace())

Upvotes: 0

Related Questions