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

mrd abd
  • 828
  • 10
  • 19

1 Answers1

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518
yshavit
  • 42,327
  • 7
  • 87
  • 124
  • what is `$1`? how use it in `String.replaceAll` – mrd abd Jun 28 '15 at 06:47
  • 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. – yshavit Jun 28 '15 at 06:49
  • The orginal code is here: https://github.com/sullo/nikto/blob/master/program/plugins/nikto_core.plugin line 3000. – mrd abd Jun 28 '15 at 06:52
  • thanks for help.. `$1` is capture group. and `String.replaceAll` doesn't support capture group. http://stackoverflow.com/a/1277171/2730925 is used instead of replaceALL. – mrd abd Jun 28 '15 at 07:09
  • 1
    `String.replaceAll` absolutely supports capture groups. `"hello world".replaceAll("l(\\w)", "_$1")` results in "he_lo wor_d". – yshavit Jun 28 '15 at 07:09
  • But yes, if you need to do some processing on each capture (for instance, parsing it and then doing some operation on that parsed value), then you need the Matcher loop approach. In your case, it looks like it'd be overkill -- but it would work. – yshavit Jun 28 '15 at 07:16