Java Regex删除开始/结束单引号但留下引号

我有来自CSV文件的数据,该文件用单引号括起来,例如:

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

我希望能够在值的开头/结尾替换单引号,但在数据中保留引号,例如:

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

我可以

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

但我想知道我是否可以将它组合起来只进行一次替换。

您可以使用运算符。

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

看看它是否适合你:)

 updateString = theString.replaceFirst("^'(.*)'$", "$1"); 

请注意,您没有的表单将无法工作,因为replace使用文字字符串,而不是正则表达式。

这通过使用捕获组(.*)来工作,在替换文本中使用$1引用。 你也可以这样做:

 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); 

当然,如果你确定在开头和结尾有一个单引号,最简单的解决方案是:

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