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.
The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.
Use the String. replaceAll() method to remove all double quotes from a string, e.g. str. replaceAll('"', '') . The replace() method will return a new string with all double quotes removed.
You can use String#replaceAll() with a pattern of ^\"|\"$ for this. string = string. replaceAll("^\"|\"$", "");
You could use the or operator.
updateString = theString.replaceAll("(^')|('$)","");
See if that works for you :)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With