Java正则表达式删除开始/结束单引号但保留内部引号

发布于 2024-09-11 09:39:07 字数 359 浏览 4 评论 0原文

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

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

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

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

我可以做

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

污味仙女 2024-09-18 09:39:07

您可以使用运算符。

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

看看这是否适合你:)

You could use the or operator.

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

See if that works for you :)

幻梦 2024-09-18 09:39:07
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);
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);
剩余の解释 2024-09-18 09:39:07

您可以使用正则表达式删除数字/数字周围的双引号。

jsonString.replaceAll("\"(\\d+)\"","$1");

如果存在负数,上述方法将不起作用。

对于负数,正则表达式会有点复杂,如下所示。但我没试过。

"([0-9]+\.{0,1}[0-9]*)"

You can use regex to remove double quotes around digits/numbers.

jsonString.replaceAll("\"(\\d+)\"","$1");

above will not work if negative numbers are present.

for negative numbers, the regex will be a little complex like below. But I haven't tried it.

"([0-9]+\.{0,1}[0-9]*)"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文