0

I would like to implement the following semantics:

while (EOF is not reached) {
    if (scanner.findWithinHorizon("^" + pattern1, 0)) {
        // do something
    } else if (scanner.findWithinHorizon("^" + pattern2, 0)) {
        // do something else
    } else {
        // report error
    }
}

Okay. The problem here is that Scanner doesn't match the new "head of the stream" with an anchored regex. For example, let's say we have a scanner new Scanner("11"). The first time we match it against the regex ^1 by calling scanner.findWithinHorizon("^1", 0) will return the matched string "1". However, the second call will return null, instead of the behavior I want, which will be returning "1" again because the new head of the stream is still '1' after consuming the first '1'.

Is there any way I can get the effect I want in Java?

Thanks in advance.

Xi Han
  • 323
  • 1
  • 7
  • Trying to understand your question , you want to match '1', you passed in '11'. you want a solution to match the first '1' and then the second '1' ? – Ibukun Muyide Apr 02 '16 at 22:12
  • Hi Ibukun. Yes. I'd like to elaborate more. Say we have '123'. If I match '2' it will be a match. But I want it to be a match only if I've matched '1' before it. – Xi Han Apr 02 '16 at 22:18

1 Answers1

0

Say we have '123'. If I match '2' it will be a match. But I want it to be a match only if I've matched '1' before it "

what you need is a lookbehind operator, this allows you to match a character based on it previous character. (?=) - positive lookahead (?<=) - positive lookbehind

if you want to match based on what is ahead also, you can use lookahead.

Here is an answer already Implementing look behind in java

Look behind Positive(?<=)

Find expression A where expression B precedes

Community
  • 1
  • 1
Ibukun Muyide
  • 1,294
  • 1
  • 15
  • 23
  • Thank you, Ibukun. I think I need to rephrase. I expect the regex only matches a `prefix` of the (string represented by the) scanner. – Xi Han Apr 02 '16 at 22:57