Kidaaaa
Kidaaaa

Reputation: 81

Regex expression in java

I want to search "$_POST['something']" in a String by regex. Tried it by textpad with following regex expression. ".*$_POST\['[a-zA-z0-9]*'\].*"

When same is used in java it is now working. ?

Upvotes: 0

Views: 96

Answers (3)

MrSnrub
MrSnrub

Reputation: 1183

You can use the regex pattern given as a String with the matches(...) method of the String class. It returns a 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)));

You can also use a Pattern and a Matcher object to reuse the pattern for multiple uses:

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("");
}

outputs:

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

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191729

You don't need the starting and trailing .*, but you do need to escape the $ as it has the special meaning of the zero-width end of the string.

\\$_POST\\['[a-zA-Z0-9]*'\\]

Upvotes: 2

frickskit
frickskit

Reputation: 624

Use this:

"\\$_POST\\['([a-zA-Z0-9]*)'\\]"

Symbols like $have particular meanings in regex. Therefore, you need to prefix them with \

Upvotes: 1

Related Questions