替换某些字符组合

Replacing certain combination of characters

我正在尝试删除其中的第一个坏字符(大写字母 + 点 + Space)。

A. Shipping Length of Unit
C. OVERALL HEIGHT
Overall Weigth
X. Max Cutting Height

我尝试过类似的方法,但它不起作用:

string.replaceAll("[A-Z]+". ", "");

结果应该是这样的:

Shipping Length of Unit
OVERALL HEIGHT
Overall Weigth
Max Cutting Height

这应该有效:

string.replaceAll("^[A-Z]\. ", "")

例子

"A. Shipping Length of Unit".replaceAll("^[A-Z]\. ", "")
// => "Shipping Length of Unit"
"Overall Weigth".replaceAll("^[A-Z]\. ", "")
// => "Overall Weigth"

试试这个:

myString.replaceAll("([A-Z]\.\s)","")
  • [A-Z] : 匹配A到Z范围内的单个字符。
  • \. : 匹配点字符。
  • \s : 匹配 space 字符。

不看你的代码就很难说出问题所在。但根据我的经验,这是我们在最初几天通常会遇到的常见问题:

String string = "A. Test String";
string.replaceAll("^[A-Z]\. ", "");
System.out.println(string);

字符串是 不可变 class Java。这意味着一旦你创建了一个对象,它就不能改变。所以在这里当我们在现有字符串中执行 replaceAll 时,它只是创建一个新的字符串对象。您需要分配给新变量或覆盖现有值,如下所示:

String string = "A. Test String";
string  = string.replaceAll("^[A-Z]\. ", "");
System.out.println(string);
input.replaceAll("[A-Z]\.\s", "");

[A-Z] 匹配从 A 到 Z 的大写字符
\. 匹配点字符
\s 匹配任何白色 space 字符

但是,这将替换与模式匹配的每个字符序列。 要在开头匹配序列,您应该使用

input.replaceAll("^[A-Z]\.\s", "");