猿问

Java:使用正则表达式获取所有字符串

我试图从 JavaScript 脚本中获取所有字符串,我创建了一个代码,但它并没有捕获所有字符串,它跳过了一些字符串


我的代码


String Strings;

    public String GetStrings(String str){

        try{

        String Str= str;

         Strings = "";

         while(true){

            Pattern pattern = Pattern.compile("('|\")");    

            Matcher matcher = pattern.matcher(Str);    

            if(matcher.find()){

                Pattern pattern1 = Pattern.compile("(" + matcher.group(1) + "[^" + matcher.group(1) + "]*" + matcher.group(1) + ")");    

                Matcher matcher1 = pattern1.matcher(Str);    

                if(matcher1.find()){

                    Strings += "|" + matcher1.group(1) + "|";

                    Str =  Str.replace(matcher1.group(1)," ");

                }

                }else{

                    break;

                    }

        }

        }catch(Exception err){return err.toString(); }

        return Strings;

        }


输入


var A="&";var B="(";var D="[]";var X="'";var W='&';var Q='';var STR="'";var Q="'******'";var G="^";var F="...";var T='$';var wm = "()"

console.log(A + B + D + "^" + wm + '#');

输出


|"&"||"("||"[]"||"'"||'&'||''||"'******'"||"^"||"..."||'$'||"()"||'#'|

正如你所看到的,没有捕获所有的字符串,有些没有出现,如果有人有任何解决方案或可以指出问题,请帮助我


波斯汪
浏览 140回答 2
2回答

GCT1015

您需要使用以下正则表达式:(\"(.*?)\")|(\'(.*?)\')例子:public String getStrings(String str){   String regex = "(\\\"(.*?)\\\")|(\\'(.*?)\\')";   Pattern pattern = Pattern.compile(regex);   Matcher matcher = pattern.matcher(str);   String output = "";   while (matcher.find()){       output = output+"|"+matcher.group(0)+"|";   }   return output;}输出:正则表达式解释|"&"||"("||"[]"||"'"||'&'||''||"'"||"'******'"||"^"||"..."||'$'||"()"||"^"||'#'|

月关宝盒

输入和预期输出不匹配,但根据我的理解是public String GetStrings(String str){&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;StringBuffer b = new StringBuffer();&nbsp; &nbsp; &nbsp; &nbsp;for (int i = 0; i < str.length(); ++i) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char ch = str.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (Character.isWhitespace(ch))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b.append("\\s");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else if (Character.isDigit(ch))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b.append("\\d");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else if (Character.isUpperCase(ch))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b.append("A-Z");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else if (Character.isLowerCase(ch))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b.append("a-z");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b.append("||");&nbsp; &nbsp; &nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答