regex group(1) problem

B

bahhab

Hi

The first code snip works but takes 4 lines and as there will be a
number of pattern matches I'd rather do each on one line. The second
snip is how I think it should work except I get "cannot resolve symbol
symbol : variable matcher". Is this possible and if so what should my
variable "matcher" be?

<snip>
Pattern regex = Pattern.compile("^(LRC[0-9]{5}).*");
Matcher match = regex.matcher(line);
boolean b = match.matches();
if (b) {id = match.group(1);}
<snip>

<snip2>
if (Pattern.compile("^(LRC[0-9]{5}).*").matcher(line).matches()) { /
id = matcher.group(1);}
<snip2>
 
H

hiwa

Hi

The first code snip works but takes 4 lines and as there will be a
number of pattern matches I'd rather do each on one line. The second
snip is how I think it should work except I get "cannot resolve symbol
symbol : variable matcher". Is this possible and if so what should my
variable "matcher" be?

<snip>
Pattern regex = Pattern.compile("^(LRC[0-9]{5}).*");
Matcher match = regex.matcher(line);
boolean b = match.matches();
if (b) {id = match.group(1);}
<snip>

<snip2>
if (Pattern.compile("^(LRC[0-9]{5}).*").matcher(line).matches()) { /
id = matcher.group(1);}
<snip2>

In your <snip2> code, Matcher object is unnamed.
 
F

Filip Larsen

(e-mail address removed) wrote
Pattern regex = Pattern.compile("^(LRC[0-9]{5}).*");
Matcher match = regex.matcher(line);
boolean b = match.matches();
if (b) {id = match.group(1);}


If you want to compact the code you can replace the variables that are
only referenced once (regex and b) with their initializer value:

Matcher matcher = Pattern.compile("^(LRC[0-9]{5}).*").matcher(line);
if (matcher.matches()) id = matcher.group(1);


Regards,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

regex problem 9
Creating a regex to get multiple values and print 0
regex 12
Why is regex so slow? 21
Java Regex Problem 7
retriving escape unicode sequences from files ... 1
RegEx problem 5
complex regex 1

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top