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

Position of the match #183

Open
RomanSoloweow opened this issue Oct 20, 2021 · 5 comments
Open

Position of the match #183

RomanSoloweow opened this issue Oct 20, 2021 · 5 comments

Comments

@RomanSoloweow
Copy link

Can I find out the position where the match was found?

@tomtheisen
Copy link

If you're writing a parser, you can get the current position using the Position property of the input (IInput). If you're not writing a parser, you might need to start. If I'm not mistaken, that's the only way to do it.

@yallie
Copy link
Member

yallie commented Oct 21, 2021

@RomanSoloweow,

Use Span() modifier to return the starting and ending positions of the parsed item.
Example:

var parser =
    from leading in Parse.WhiteSpace.Many()
    from span in Parse.Identifier(Parse.Letter, Parse.LetterOrDigit).Span()
    from trailing in Parse.WhiteSpace.Many()
    select span;

var r = parser.TryParse("  Hello!");
var id = r.Value;
Assert.Equal("Hello", id.Value);
Assert.Equal(5, id.Length);

// span.Start is the starting position
Assert.Equal(2, id.Start.Pos);
Assert.Equal(1, id.Start.Line);
Assert.Equal(3, id.Start.Column);

// span.End is the ending position
Assert.Equal(7, id.End.Pos);
Assert.Equal(1, id.End.Line);
Assert.Equal(8, id.End.Column);

@yallie
Copy link
Member

yallie commented Oct 21, 2021

Parse.Span return value looks like this:

public interface ITextSpan<T>
{
    T Value { get; }
    Position Start { get; }
    Position End { get; }
    int Length { get; }
}

@RomanSoloweow
Copy link
Author

Is there an example of how to use it?
I need to check for matches and, if successful, return the position of the matches found

@yallie
Copy link
Member

yallie commented Oct 21, 2021

Just append .Span() to any existing parser like I posted before:

var parser =
    from leading in Parse.WhiteSpace.Many()
    from span in Parse.Identifier(Parse.Letter, Parse.LetterOrDigit).Span() // <- here
    from trailing in Parse.WhiteSpace.Many()
    select span;

The parser above will return ITextSpan<string> instead of just string.
So you'll get the parsed value with the position and length of its span.
For more examples, please check out the unit tests in this repository.

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

3 participants