怎样仅删除字符串开头和结尾的特殊字符?

huangapple go评论64阅读模式
英文:

How to remove only starting and ending special character from a string?

问题

我想要移除只位于开头的特殊字符,即 ",和只位于结尾的特殊字符 "。
给定的输入字符串为

String input= "\"This#string%contains^special*characters&.\"";

期望的输出为

String output= "This#string%contains^special*characters&.";

有人可以帮我通过正则表达式或其他方式在Java中实现这一点吗?

英文:

I want to remove only the starting special character i.e. " and ending special character ".
The given input string is

String input= "\"This#string%contains^special*characters&.\"";

The expected output is

String output= "This#string%contains^special*characters&.";

Can any one help me how to do this using regex or any other way to remove only starting and ending special character only from the input string in java.

答案1

得分: 2

我会使用正则表达式方法:

String input = "This#string%contains^special*characters&.";
String output = input.replaceAll("^[^A-Za-z0-9]|[^A-Za-z0-9]$", "");
System.out.println(output);

这将打印出:

This#string%contains^special*characters&.
英文:

I would use a regex approach:

String input= "\"This#string%contains^special*characters&.\"";
String output = input.replaceAll("^[^A-Za-z0-9]|[^A-Za-z0-9]$", "");
System.out.println(output);

This prints:

This#string%contains^special*characters&.

huangapple
  • 本文由 发表于 2020年9月12日 17:14:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63858732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定