Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 49189
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T16:23:52+00:00 2026-05-10T16:23:52+00:00

Lexical analyzers are quite easy to write when you have regexes. Today I wanted

  • 0

Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with:

import re import sys  class Token(object):     ''' A simple Token structure.         Contains the token type, value and position.      '''     def __init__(self, type, val, pos):         self.type = type         self.val = val         self.pos = pos      def __str__(self):         return '%s(%s) at %s' % (self.type, self.val, self.pos)   class LexerError(Exception):     ''' Lexer error exception.          pos:             Position in the input line where the error occurred.     '''     def __init__(self, pos):         self.pos = pos   class Lexer(object):     ''' A simple regex-based lexer/tokenizer.          See below for an example of usage.     '''     def __init__(self, rules, skip_whitespace=True):         ''' Create a lexer.              rules:                 A list of rules. Each rule is a `regex, type`                 pair, where `regex` is the regular expression used                 to recognize the token and `type` is the type                 of the token to return when it's recognized.              skip_whitespace:                 If True, whitespace (\s+) will be skipped and not                 reported by the lexer. Otherwise, you have to                  specify your rules for whitespace, or it will be                 flagged as an error.         '''         self.rules = []          for regex, type in rules:             self.rules.append((re.compile(regex), type))          self.skip_whitespace = skip_whitespace         self.re_ws_skip = re.compile('\S')      def input(self, buf):         ''' Initialize the lexer with a buffer as input.         '''         self.buf = buf         self.pos = 0      def token(self):         ''' Return the next token (a Token object) found in the              input buffer. None is returned if the end of the              buffer was reached.              In case of a lexing error (the current chunk of the             buffer matches no rule), a LexerError is raised with             the position of the error.         '''         if self.pos >= len(self.buf):             return None         else:             if self.skip_whitespace:                 m = self.re_ws_skip.search(self.buf[self.pos:])                  if m:                     self.pos += m.start()                 else:                     return None              for token_regex, token_type in self.rules:                 m = token_regex.match(self.buf[self.pos:])                  if m:                     value = self.buf[self.pos + m.start():self.pos + m.end()]                     tok = Token(token_type, value, self.pos)                     self.pos += m.end()                     return tok              # if we're here, no rule matched             raise LexerError(self.pos)      def tokens(self):         ''' Returns an iterator to the tokens found in the buffer.         '''         while 1:             tok = self.token()             if tok is None: break             yield tok   if __name__ == '__main__':     rules = [         ('\d+',             'NUMBER'),         ('[a-zA-Z_]\w+',    'IDENTIFIER'),         ('\+',              'PLUS'),         ('\-',              'MINUS'),         ('\*',              'MULTIPLY'),         ('\/',              'DIVIDE'),         ('\(',              'LP'),         ('\)',              'RP'),         ('=',               'EQUALS'),     ]      lx = Lexer(rules, skip_whitespace=True)     lx.input('erw = _abc + 12*(R4-623902)  ')      try:         for tok in lx.tokens():             print tok     except LexerError, err:         print 'LexerError at position', err.pos 

It works just fine, but I’m a bit worried that it’s too inefficient. Are there any regex tricks that will allow me to write it in a more efficient / elegant way ?

Specifically, is there a way to avoid looping over all the regex rules linearly to find one that fits?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T16:23:52+00:00Added an answer on May 10, 2026 at 4:23 pm

    You can merge all your regexes into one using the ‘|’ operator and let the regex library do the work of discerning between tokens. Some care should be taken to ensure the preference of tokens (for example to avoid matching a keyword as an identifier).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a simple language that I'm using Flex(Lexical Analyzer), it's like this: /*
I have written simple lexical analyzer. And I understand the need to provide each
I'm trying to build a simple lexical analyzer to go along with a simple
I need to implement compiler (lexical, syntax and semantic analyzers). I have already implemented
I'm learning to write a lexical analyzer generator (a clone of lex), based on
I have a school assignment which consists of programming a scanner/lexical analyzer for a
I am trying to create a lexical analyzer program using java.Program must have the
I'm trying to install flex (the lexical analyzer, not the Adobe program) on my
There are many lexical analyzer and parser generators out there - lex/flex and yacc/bison,
Are you aware of any lexical analyzer or lexer in Qt? I need it

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.