0

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. ?

1

3 Answers 3

2

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]*'\\]
Sign up to request clarification or add additional context in comments.

Comments

1

Use this:

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

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.