regex - Why isn't this lookahead assertion working in Java? -


i come perl background , used doing following match leading digits in string , perform in-place increment one:

my $string = '0_beginning';  $string =~ s|^(\d+)(?=_.*)|$1+1|e;  print $string;        # '1_beginning' 

with limited knowledge of java, things aren't succinct:

string string = "0_beginning";  pattern p = pattern.compile( "^(\\d+)(?=_.*)" );  string digit = string.replacefirst( p.tostring(), "$1" ); // digit  integer onemore = integer.parseint( digit ) + 1;          // evaluate ++digit  string.replacefirst( p.tostring(), onemore.tostring() );  // 

the regex doesn't match here... did in perl.

what doing wrong here?

actually matches. can find out printing

system.out.println(p.matcher(string).find()); 

the issue line

string digit = string.replacefirst( p.tostring(), "$1" ); 

which do-nothing, because replaces first group (which match, lookahead not part of match) content of first group.

you can desired result (namely digit) via following code

matcher m = p.matcher(string); string digit = m.find() ? m.group(1) : ""; 

note: should check m.find() anyways if nothing matches. in case may not call parseint , you'll error. full code looks like

pattern p = pattern.compile("^(\\d+)(?=_.*)");  string string = "0_beginning";  matcher m = p.matcher(string); if (m.find()) {     string digit = m.group(1);     integer onemore = integer.parseint(digit) + 1;     string = m.replaceall(onemore.tostring());     system.out.println(string); } else {     system.out.println("no match"); } 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -