正则表达式不考虑空间
问题描述:
我在Java中,以下正则表达式 -正则表达式不考虑空间
Pattern p = Pattern.compile("int|float|char\\s\\w");
但仍这是符合“intern
”了。
整个代码 -
package regex;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class Regex {
public static void main(String[] args) throws IOException{
// TODO code application logic here
int c = 0;
BufferedReader bf = new BufferedReader(new FileReader("new.c"));
String line;
Pattern p = Pattern.compile("int|float|char\\s\\w");
Matcher m;
while((line = bf.readLine()) != null) {
m = p.matcher(line);
if(m.find()) {
c++;
}
}
System.out.println(c);
}
}
答
我假设你的意思是找到替代品之一,然后是空间和一个字。
但
你可以从该\s\w
仅适用于char
替代列表中看到。
为了解决这个问题,使\s\w
外组,因此它适用于所有
的替代品。
(?:
int
| # or,
float
| # or,
char
)
\s \w
最后的正则表达式是那么"(?:int|float|char)\\s\\w"
答
环绕像括号中的选项,以便:
Pattern p = Pattern.compile("(int|float|char)\\s\\w");
此外,如果你想覆盖一些边缘情况下,为了应对一些不好的格式代码你可以使用:
Pattern p = Pattern.compile("^(\\s|\\t)*(int|float|char)(\\s|\\t)+[a-zA-Z_][a-zA-Z0-9_]*(\\s|\\t)*");
这应该涵盖那里的情况在类型和变量名称之间多于一个空格或制表符,并且还包括以下划线开头的变量名称,以及“int”“float”或“char”是某个单词的结尾的情况。
不是重复的,引用的问题是关于贪婪,这个是关于运算符的优先级。 – SJuan76
尝试发布文件内容,然后你想阅读,以帮助解答 – Abe
[正则表达式只匹配整个单词](https://stackoverflow.com/questions/1751301/regex-match-entire-words-only )。所有你需要的是''int \\ b | float | char \\ s \\ w“'以避免在'intern'中匹配'int'。 –