Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex to remove start/end single quotes but leave inside quotes

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.

like image 736
George Avatar asked Jul 23 '10 02:07

George


People also ask

How do you remove the first and last quotes of a string in Java?

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.

How do you remove the beginning and end of a string in quotes?

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.

How do you remove leading and trailing quotes in Java?

You can use String#replaceAll() with a pattern of ^\"|\"$ for this. string = string. replaceAll("^\"|\"$", "");


2 Answers

You could use the or operator.

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

See if that works for you :)

like image 59
Josiah Avatar answered Oct 23 '22 20:10

Josiah


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);
like image 36
Matthew Flaschen Avatar answered Oct 23 '22 18:10

Matthew Flaschen