Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

StringScanner does not find the corresponding data #43

Closed
xuyisheng opened this issue Mar 22, 2022 · 3 comments
Closed

StringScanner does not find the corresponding data #43

xuyisheng opened this issue Mar 22, 2022 · 3 comments

Comments

@xuyisheng
Copy link

StringScanner lost data with the code below:

var content = 'xxxx[fn=4][fn=37][fn=36][fn=12][fn=26]xxxx';

var _scanner = StringScanner(content);
    while (!_scanner.isDone) {
      if (_scanner.scan(RegExp('\\[fn=(\\d+)]'))) {
        print(content.substring(_scanner.lastMatch!.start + 1, _scanner.lastMatch!.end - 1));
      }
      if (!_scanner.isDone) {
        _scanner.position++;
      }
    }

the result is :

I/flutter (25050): fn=4
I/flutter (25050): fn=36
I/flutter (25050): fn=26

but If I use this method directly:

var allMatches = RegExp('\\[fn=(\\d+)]').allMatches(content);
    for (var element in allMatches) {
      print('--${element.start}');
    }

I got the right answer:

I/flutter (25050): [fn=4]
I/flutter (25050): [fn=37]
I/flutter (25050): [fn=36]
I/flutter (25050): [fn=12]
I/flutter (25050): [fn=26]

something lost when I use StringScanner.

@jolleekin
Copy link

Please try this code

      if (_scanner.scan(RegExp('\\[fn=(\\d+)]'))) {
        print(content.substring(_scanner.lastMatch!.start + 1, _scanner.lastMatch!.end - 1));
      } else {
        _scanner.position++;
      }

Some methods move the pointer forward while others don't.

@xuyisheng
Copy link
Author

Please try this code

      if (_scanner.scan(RegExp('\\[fn=(\\d+)]'))) {
        print(content.substring(_scanner.lastMatch!.start + 1, _scanner.lastMatch!.end - 1));
      } else {
        _scanner.position++;
      }

Some methods move the pointer forward while others don't.

It works! thank u very much~

ps: Is StringScaner more efficient than using regular expressions directly?

@jolleekin
Copy link

Looking at your code, I can say you should use RegExp directly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants