如果我有一个名为 tokenArray 的字符串数组。其内容如下
<小时/>[num1] [;] ["] [此] [是] [a] [\"] [字符串] [文字] [\"] [.] [?] ["]
<小时/>注意:非转义双引号和转义双引号保持原样。
问题:
如何将数组中两个双引号之间的值识别为单个字符串文字?, .我使用字符串连接来保存找到的临时词素,并最终在找到匹配时保存到堆栈。在我的例子中,在开始和结束匹配的//和 tHiS_iS_tHe_EnD_Of_NeWlInE 之前识别单行注释。如何将它与带有两个双引号的正则表达式一起应用,就像上面我在下面放置的代码中的循环内一样。 TIA。
背景:
只是我找到的样本是单个字符串声明的形式,而我的样本是在数组中。我不太明白它是如何处理字符串数组的。
顺便说一句。我正在制作一个字符串分析器,它扫描代码块并输出特定语言的词位。除了分隔符和没有正则表达式的语言的一些关键字之外,我已经识别了每个词素,例如单个注释和 block 注释。但我想尝试使用正则表达式来获取我尚未检测到的字符串文字。通过 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()+"\n\t -> \t This is a String Literal\n");
}
}
关于java - 如何使用 Java 上的正则表达式识别数组中的字符串文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46639548/