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.
qr
, check out Pattern.compile
, which throws a PatternSyntaxException if the given string isn't a valid regex. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.