我想通过正则表达式在字符串中搜索“$_POST['something']”。使用以下正则表达式通过文本板进行了尝试。".*$_POST\['[a-zA-z0-9]*'\].*"
当在java中使用相同时,它现在正在工作。?
您不需要开头和结尾.*
,但您确实需要转义 ,$
因为它具有字符串零宽度结尾的特殊含义。
\\$_POST\\['[a-zA-Z0-9]*'\\]
用这个:
"\\$_POST\\['([a-zA-Z0-9]*)'\\]"
像这样的符号$
在正则表达式中有特定的含义。因此,您需要在它们前面加上\
您可以将作为字符串给出的正则表达式模式与String 类的match(...) 方法一起使用。它返回一个.boolean
String a = "Hello, world! $_POST['something'] Test!";
String b = "Hello, world! $_POST['special!!!char'] Test!";
String c = "Hey there $_GET['something'] foo bar";
String pattern = ".*\\$_POST\\['[A-Za-z0-9]+'\\].*";
System.out.println ("a matches? " + Boolean.toString(a.matches(pattern)));
System.out.println ("b matches? " + Boolean.toString(b.matches(pattern)));
System.out.println ("c matches? " + Boolean.toString(c.matches(pattern)));
您还可以使用Pattern和 Matcher 对象来重用模式以供多种用途:
String[] array = {
"Hello, world! $_POST['something'] Test!",
"Hello, world! $_POST['special!!!char'] Test!",
"Hey there $_GET['something'] foo bar"
};
String strPattern = ".*\\$_POST\\['[A-Za-z0-9]+'\\].*";
Pattern p = Pattern.compile(strPattern);
for (int i=0; i<array.length; i++) {
Matcher m = p.matcher(array[i]);
System.out.println("Expression: " + array[i]);
System.out.println("-> Matches? " + Boolean.toString(m.matches()));
System.out.println("");
}
输出:
Expression: Hello, world! $_POST['something'] Test!
-> Matches? true
Expression: Hello, world! $_POST['special!!!char'] Test!
-> Matches? false
Expression: Hey there $_GET['something'] foo bar
-> Matches? false