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

后端 未结 2 1499
后悔当初
后悔当初 2020-12-20 17:39

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

相关标签:
2条回答
  • 2020-12-20 18:18

    You could use the or operator.

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

    See if that works for you :)

    0 讨论(0)
  • 2020-12-20 18:19
    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);
    
    0 讨论(0)
提交回复
热议问题