-1

I want to rewrite a perl code in java:

sub validate_and_fix_regex {
    my $regex = $_[0];
    eval { qr/$regex/ };
    if ($@) {
        $regex = rquote($regex);
    }
    return $regex;
}

sub rquote {
    my $string = $_[0] || return;
    $string =~ s/([^A-Za-z_0-9 "'\\])/\\$1/g;
    return $string;
}

the code gets a regex and fix it if it has any escaped character. i cant find any alternative for eval { qr/$regex/ }; and $string =~ s/([^A-Za-z_0-9 "'\\])/\\$1/g; in java.

0

1 Answer 1

2
  • For qr, check out Pattern.compile, which throws a PatternSyntaxException if the given string isn't a valid regex.
  • For s///, check out String.replaceAll.
  • eval BLOCK is named try in Java.

Putting it all together: you would want to invoke Pattern.compile in the body of a try-catch. If you catch a PatternSyntaxExpression, you would invoke rquote, and use String.replaceAll there.

Sign up to request clarification or add additional context in comments.

6 Comments

what is $1? how use it in String.replaceAll
Do you know what it is in the original perl you posted? If not, that would be where to start, but that's a different question, and I'd recommend you read up on Perl's regexes (and regexes in general). If you do understand that, I'm not sure what the question is -- the String.replaceAll docs link to plenty of good docs.
The orginal code is here: github.com/sullo/nikto/blob/master/program/plugins/… line 3000.
thanks for help.. $1 is capture group. and String.replaceAll doesn't support capture group. stackoverflow.com/a/1277171/2730925 is used instead of replaceALL.
String.replaceAll absolutely supports capture groups. "hello world".replaceAll("l(\\w)", "_$1") results in "he_lo wor_d".
|

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.