如果我有一个名为tokenArray的字符串数组。其内容如下
[num1][;]["][此][是][a][\"][string][literal][\"][.][?]["]
注意:非转义和转义双引号是原样。
问题:
如何将数组中两个双引号之间的值标识为单个字符串文字。我使用字符串串联来保存找到的临时词法,最后在找到匹配项时保存到堆栈。在我的情况下,在开始和结束匹配的//和tHiS_iS_the_EnD_of_NeWlInE之前识别单行注释。我如何将其应用于带有两个双引号的regex,就像上面一样,在我下面放入的代码中的循环中。TIA。
背景:
只是我发现的样本是一个单一的String声明形式,而我的样本是在一个数组中。我不太明白它是如何处理一组字符串的。
顺便说一句。我正在制作一个字符串分析器,它扫描一块代码并输出特定语言的词法。除了没有正则表达式的语言的分隔符和一些关键字之外,我已经确定了每个词法,如单个和块注释。但是我想为我还没有检测到的字符串文本尝试regex。通过if和else语句应用检测非常耗时且令人困惑,但我做到了最少。
下面是我用来识别数组中单行注释的代码。for循环是我读取数组并将新检测到的词位分配给堆栈的整个循环。
for(int ctr=0;ctr<removedNullsStackSize.length;ctr++) {
if(removedNullsStackSize[ctr].equals("//")) {
do {
tempString = tempString + " " + removedNullsStackSize[ctr] ;
ctr++;
if(ctr>=removedNullsStackSize.length-1){
removedNullsStackSize[ctr]="tHiS_iS_tHe_EnD_Of_NeWlInE";
}
}
while(removedNullsStackSize[ctr]!="tHiS_iS_tHe_EnD_Of_NeWlInE");
myQCommentsTokenized.add(tempString);
tempString="";
}
在上面的代码中,它所做的是在检测到//时连接前面的数组,并且在检测到换行符之前不会停止连接。如果检测到换行符,它会将要堆栈的临时字符串保存为找到的新词法。
我的模式是.
//Regex for identifying string literals
Pattern strRegex=Pattern.compile("".*"");
//Loop your array here to read code
//str is the temporary location of all the codes you have
//In mine, I have it inside a text area so I just typecasted it to string and start comparing there
//begins matching` for string literals that is in the strRegex
Matcher m = strRegex.matcher(str) ;
在读取代码之后,它将拥有所读取代码中字符串文字的词法。
while (m.find()) {
String forReadStr=m.group();
//If the end of the token is a double quote, Do this
//in this loop, you can then declare anything for the lexeme you detected and do anything with it
if(forReadStr.endsWith(""")){
System.out.println(m.group()+"nt -> t This is a String Literaln");
}
}