简体   繁体   English

从多行字符串中删除前导特殊字符

[英]Remove leading special characters from multiline string

Working on XSS vulnerability in which I have a requirement to remove all the leading special characters only.处理 XSS 漏洞,其中我要求仅删除所有前导特殊字符。 No need to remove the special characters at the end or in between.无需删除末尾或中间的特殊字符。 Alphanumeric is allowed but no special characters at the beginning.允许使用字母数字,但不能以特殊字符开头。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main
{
        
public static void main(String args[])   {  
String str=   "**$*****Important****\n"
             + " document is not uploaded \n"
             + "%3Cscript%3E";    
str = str.replaceAll("[^a-zA-Z0-9\\s]", " ");  
System.out.println(str);  

 }  
}

The code above gives output as:上面的代码给出的输出为:

Important重要的

But the expected output is:但预期的输出是:

Important**** document is not uploaded 3Cscript%3E重要****文件未上传 3Cscript%3E

How can I fix this?我怎样才能解决这个问题?

There are three changes you need to make:您需要进行三项更改:

  1. Anchor the match to the beginning of the string with ^ .使用^将匹配锚定到字符串的开头。
  2. Match more than one special character with + .+匹配多个特殊字符。
  3. Replace the matched substring with "" instead of " " :""而不是" "替换匹配的子字符串:
    str = str.replaceAll("^[^a-zA-Z0-9\\s]+", "");  

你可能需要

str = str.replaceAll("(?m)^[^a-zA-Z0-9\\s]+", " ");   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM