繁体   English   中英

如何从输入文本中删除特殊字符

[英]How to remove special characters from input text

我想从输入文本中删除所有特殊字符以及一些受限制的单词。

无论我要删除什么,它都会动态变化

(让我澄清一下:无论我需要排除哪些词,这些词都会动态提供-用户将决定需要排除的词。这就是我不包括regex的原因。strict_words_list(请参阅我的代码)将从数据库中获取只是为了检查代码是否正常工作(我一直保持静态),

但是出于演示目的,我将它们保留在String数组中,以确认我的代码是否正常运行。

public class TestKeyword {

    private static final String[] restricted_words_list={"@","of","an","^","#","<",">","(",")"};

    private static final Pattern restrictedReplacer;

    private static Set<String> restrictedWords = null;

    static {

        StringBuilder strb= new StringBuilder();

        for(String str:restricted_words_list){
            strb.append("\\b").append(Pattern.quote(str)).append("\\b|");
        }

        strb.setLength(strb.length()-1);
        restrictedReplacer = Pattern.compile(strb.toString(),Pattern.CASE_INSENSITIVE);

        strb = new StringBuilder();    
    }

    public static void main(String[] args)
    {
        String inputText = "abcd abc@ cbda ssef of jjj t#he g^g an wh&at ggg<g ss%ss ### (()) D^h^D";
        System.out.println("inputText : " + inputText);
        String modifiedText = restrictedWordCheck(inputText);
        System.out.println("Modified Text : " + modifiedText);

    }

    public static String restrictedWordCheck(String input){
        Matcher m = restrictedReplacer.matcher(input);
        StringBuffer strb = new StringBuffer(input.length());//ensuring capacity

        while(m.find()){
            if(restrictedWords==null)restrictedWords = new HashSet<String>();
            restrictedWords.add(m.group());  //m.group() returns what was matched
            m.appendReplacement(strb,""); //this writes out what came in between matching words

            for(int i=m.start();i<m.end();i++)
                strb.append("");
        }
        m.appendTail(strb);
        return strb.toString();
    }
}

输出为:

inputText:jjj的abcd abc @ cbda ssef g ^ g wh&at ggg

修改后的文本:abcd abc @ cbda ssef jjj gg wh&at gggg ss%ss ###(())DhD

在这里,排除词是 ,但只有一些特殊字符,而不是所有的,我在指定restricted_words_list


现在我有了一个更好的解决方案:

    String inputText = title;// assigning input 
    List<String> restricted_words_list = catalogueService.getWordStopper(); // getting all stopper words from database dynamically (inside getWordStopper() method just i wrote a query and getting list of words)
    String finalResult = "";
    List<String> stopperCleanText = new ArrayList<String>();

    String[] afterTextSplit = inputText.split("\\s"); // split and add to list

    for (int i = 0; i < afterTextSplit.length; i++) {
        stopperCleanText.add(afterTextSplit[i]); // adding to list
    }

    stopperCleanText.removeAll(restricted_words_list); // remove all word stopper 

    for (String addToString : stopperCleanText)
    {
        finalResult += addToString+";"; // add semicolon to cleaned text 
    }

    return finalResult;
public String replaceAll(String regex,
                         String replacement)

用给定的替换替换该字符串的每个子字符串(与给定的正则表达式匹配)。

参数:

  • regex此字符串要匹配的正则表达式
  • replacement用于每次匹配的字符串。

因此,您只需要为替换参数提供一个空字符串即可。

您可能考虑直接使用Regex将那些特殊字符替换为空的?? 签出: Java; 字符串替换(使用正则表达式)? ,此处提供一些教程: http : //www.vogella.com/articles/JavaRegularExpressions/article.html

您也可以这样:

    String inputText = "abcd abc@ cbda ssef of jjj t#he g^g an wh&at ggg<g ss%ss ### (()) D^h^D";        
    String regx="([^a-z^ ^0-9]*\\^*)";        
    String textWithoutSpecialChar=inputText.replaceAll(regx,"");
    System.out.println("Without Special Char:"+textWithoutSpecialChar);

    String yourSetofString="of|an";   // your restricted words.      
    String op=textWithoutSpecialChar.replaceAll(yourSetofString,"");
    System.out.println("output : "+op);

o / p:

Without Special Char:abcd abc cbda ssef of jjj the gg an what gggg ssss   h

output : abcd abc cbda ssef  jjj the gg  what gggg ssss   h
String s = "abcd abc@ cbda ssef of jjj t#he g^g an wh&at ggg (blah) and | then";

String[] words = new String[]{ " of ", "|", "(", " an ", "#", "@", "&", "^", ")" };
StringBuilder sb = new StringBuilder();
for( String w : words ) {
    if( w.length() == 1 ) {
        sb.append( "\\" );
    }
    sb.append( w ).append( "|" );
}
System.out.println( s.replaceAll( sb.toString(), "" ) );

你应该改变你的循环

for(String str:restricted_words_list){
        strb.append("\\b").append(Pattern.quote(str)).append("\\b|");
}

对此:

for(String str:restricted_words_list){
        strb.append("\\b*").append(Pattern.quote(str)).append("\\b*|");
}

因为在循环中,只有在匹配之前之后都有匹配项,您才匹配restricted_words_list元素。 由于abc@@之后没有任何内容,因此不会被替换。 如果在任一侧的\\\\b上添加* (表示0次或多次),则也将匹配abc@类的内容。

暂无
暂无

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

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