• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 352
  • Last Modified:

Matcher.start(int group)

Hi Experts ..

java.util.regex.Matcher.start(int group) method throws IllegalStateException if "If no match has been attempted, or if the previous match operation failed."

could someone please give me example for that case??
0
DrAske
Asked:
DrAske
  • 4
  • 3
  • 2
  • +1
3 Solutions
 
cavey_79Commented:
When you just create the matcher, without calling methods like matches, or when you call them and they return false.
0
 
CEHJCommented:
Pattern p = Pattern.compile("(\\d)");
Matcher m = p.matcher("abc");
m.start(1);
0
 
cavey_79Commented:
In other words, you will need to successfully do one of these three operations:
      The matches method attempts to match the entire input sequence against the pattern.
      The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern.
      The find method scans the input sequence looking for the next subsequence that matches the pattern.

before you can call start, group, etc.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
CEHJCommented:
There are no digits in "abc" so the match will fail and thus the call to start throws the exception
0
 
objectsCommented:
From the javadoc it "Returns the start index of the subsequence captured by the given group during the previous match operation.".
So if there is no successful previous match operation then it cannot return the start index, in which case it will throw the exception.
0
 
DrAskeAuthor Commented:
Thanks for all of you :o) so I can avoid it using find() method,
then the following will not throw the exception cause the while condition will be false

Pattern pattern = Pattern.compile("(\\d)");
Matcher matcher = pattern.matcher("abc");
 while(matcher.find()){
            int start = matcher.start(1);
            int end = matcher.end(1);
}

really appreciate your help,
regards,
0
 
cavey_79Commented:
If you don't need to match it repeatedly, you can do this:
if (matcher.matches()){
          int start = matcher.start(1);
          int end = matcher.end(1);
}
0
 
objectsCommented:
that is correct
0
 
CEHJCommented:
>>then the following will not throw the exception cause the while condition will be false

Correct
0
 
CEHJCommented:
:-)
0
 
DrAskeAuthor Commented:
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 4
  • 3
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now