Java Regex删除开始/结束单引号,但保留内引号

时间:2022-09-15 16:14:58

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

我有一个包含在单引号中的CSV文件的数据,比如:

'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.

但是我想知道我是否可以把它组合成一个替换。

2 个解决方案

#1


16  

You could use the or operator.

你可以用or运算符。

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

See if that works for you :)

看看对你是否有效:)

#2


1  

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

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

注意,您没有的表单不能工作,因为replace使用文字字符串,而不是regexes。

This works by using a capturing group (.*), which is referred to with $1 in the replacement text. You could also do something like:

这可以通过使用捕获组(.*)来工作,在替换文本中使用$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);

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

#1


16  

You could use the or operator.

你可以用or运算符。

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

See if that works for you :)

看看对你是否有效:)

#2


1  

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

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

注意,您没有的表单不能工作,因为replace使用文字字符串,而不是regexes。

This works by using a capturing group (.*), which is referred to with $1 in the replacement text. You could also do something like:

这可以通过使用捕获组(.*)来工作,在替换文本中使用$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);

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