Java Regex to remove single start and end quotes, but leave quotes inside

I have data from a CSV file enclosed in single quotes, for example:

'Company name' 'Price: $43.50' 'New York, New York' 

I want to be able to replace single quotes at the beginning / end of a value, but leave quotes in the data, for example:

 'Joe Diner' should become Joe Diner 

I can do

 updateString = theString.replace("^'", "").replace("'$", ""); 

but I wanted to know if I could combine it to make only one replacement.

+7
java regex replace csv
source share
2 answers

You can use the or operator.

 updateString = theString.replaceAll("(^')|('$)",""); 

See if this works for you :)

+16
source share
 updateString = theString.replaceFirst("^'(.*)'$", "$1"); 

Note that a form that you don't have will not work, because replace uses literals, not regular expressions.

This works with the capture group (.*) Referenced by $1 in the replacement text. You can also do something like:

 Pattern patt = Pattern.compile("^'(.*)'$"); // could be stored in a static final field. Matcher matcher = patt.matcher(theString); boolean matches = matcher.matches(); updateString = matcher.group(1); 

Of course, if you are sure that there is one quote at the beginning and the end, the simplest solution is:

 updateString = theString.substring(1, theString.length() - 1); 
+1
source share

All Articles