replaceFirst() 和 trim().replaceFirst() 之间的区别

difference between replaceFirst() and trim().replaceFirst()

我在乱用正则表达式并在字符串的开头截断经过恶意编码的字符。我遇到了不同的实现:

String Str = new String(".,,¨B<?xml version='1.0' encoding='UTF-8'?> 
str.replaceFirst("(.*)<?xml","<?xml");
str.trim().replaceFirst("(.*)<?xml","<?xml")

输出保持不变。这里有什么区别,应该使用哪一个?

trim() 方法删除前导和尾随空格。在您的情况下,不同之处在于它删除了 尾随空格 ,因为您的替换正则表达式将匹配 <?xml.

之前的任何字符(包括空格)

顺便说一句,您应该将正则表达式更改为 ".*?<\?xml",原因如下:

  1. 你必须转义?,否则它具有使<可选的特殊含义。所以你的正则表达式将匹配 "hello xml abc",返回“
  2. 你必须使前面的表达式非贪婪(或"reluctant"),这是通过将.*更改为.*?来完成的。尝试使用 "abc <?xml def <?xml ghi" 的输入 str,您会看到差异。
  3. 括号是不必要的。如果你愿意,你可以保留它们。

没有区别...trim() returns a String,然后您依次调用 replaceFirst();就像直接调用String.replaceFirst()一样。

至于方法的功能,trim() 将在 String.

的边缘(开始和结束)删除 (trim) 个不需要的空白字符

String.trim() 方法从字符串中删除尾随和前导空格。但是由于您正在测试的字符串没有任何尾随或前导空格,因此下面两个肯定 return 相同的字符串。

str.replaceFirst("(.*)<?xml","<?xml");
str.trim().replaceFirst("(.*)<?xml","<?xml")

但是,您的正则表达式只删除前导空格,因此如果测试字符串有尾随空格,结果会有所不同。例如:

String str = new String("   .,,¨B<?xml version='1.0' encoding='UTF-8'?>  ");
    String str1 = str.replaceFirst("(.*)<?xml", "<?xml");
    String str2 = str.trim().replaceFirst("(.*)<?xml", "<?xml");

    System.out.println(str1 + "|");
    System.out.println(str2 + "|");

给你,注意第一个结果仍然有尾随空格。

<?xml version='1.0' encoding='UTF-8'?>  |
<?xml version='1.0' encoding='UTF-8'?>|

首先你要了解两种方法:

  1. trim() -> return 删除前导和尾随白色 space 的此字符串的副本,或者此字符串,如果它没有前导或尾随白色 space .
  2. replaceFirst(String regex,String replacement) -> 用给定的替换替换此字符串中与给定正则表达式匹配的第一个子字符串。

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("===========replaceFirst=============");
    String test1 = "I am a teacher in a secondary school";
    String out1 = test1.replaceFirst("a", "an");
    System.out.println(out1);
    System.out.println("===========trim.replaceFirst=============");
    String test2 = "I am a teacher in a secondary school";
    String out2 = test2.trim().replaceFirst("a", "an");
    System.out.println(out2);
}

输出控制台:

===========replaceFirst=============
I anm a teacher in a secondary school
===========trim.replaceFirst=============
I anm a teacher in a secondary school

所以,replaceFirst()trim().replaceFirst()没有区别。