8

I have data from a CSV file that is enclosed in single quotes, like:

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

I want to be able to replace the single quotes at the start/end of the value but leave quotes in the data, like:

'Joe's Diner'  should become Joe's Diner

I can do

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

but I wanted to know if I could combine it to only do one replace.

finnw
  • 47,861
  • 24
  • 143
  • 221
George
  • 81
  • 1
  • 1
  • 2
  • You want to allow unbalanced quotes *and* use quotes to escape commas within a cell? It is not possible to do both at once. – finnw Jul 23 '10 at 17:36
  • Yes, you can combine them quite easily. Have another look at @Josiah's answer, now that he's using the correct method. – Alan Moore Jul 23 '10 at 22:07

3 Answers3

17

You could use the or operator.

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

See if that works for you :)

Josiah
  • 4,754
  • 1
  • 20
  • 19
1
updateString = theString.replaceFirst("^'(.*)'$", "$1");

Note that the form you have no won't work because replace uses literal strings, not regexes.

This works by using a capturing group (.*), which is referred to with $1 in the replacement text. You could 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're certain there's a single quote at the beginning and end, the simplest solution is:

updateString = theString.substring(1, theString.length() - 1);
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
0

You can use regex to remove double quotes around digits/numbers.

jsonString.replaceAll("\"(\\d+)\"","$1");

above will not work if negative numbers are present.

for negative numbers, the regex will be a little complex like below. But I haven't tried it.

"([0-9]+\.{0,1}[0-9]*)"
Prakash Palnati
  • 3,231
  • 22
  • 35