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

  • Home
  • SEARCH
  • 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 6605751
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T19:19:17+00:00 2026-05-25T19:19:17+00:00

I am trying to parse C++/Java style source files and would like to isolate

  • 0

I am trying to parse C++/Java style source files and would like to isolate comments, string literals, and whitespaces as tokens.

For whitespaces and comments, the commonly suggested solution is (using ANTLR grammar):

// WS comments*****************************
WS: (' '|'\n'| '\r'|'\t'|'\f' )+ {$channel=HIDDEN;};
ML_COMMENT: '/*' (options {greedy=false;}: .)* '*/' {$channel=HIDDEN;};
SL_COMMENT: '//' (options {greedy=false;}: .)* '\r'? '\n' {$channel=HIDDEN;};

But, the problem is that my source files also consist of string literals e.g.

printf("   /* something looks like comment and whitespace \n");
printf("    something looks like comment and whitespace */ \n");

The whole thing inside “” should be considered a single token but my ANTLR lexer rules obviously will consider them a ML_COMMENT token:

    /* something looks like comment and whitespace \n");
printf("    something looks like comment and whitespace */

But I cannot create another lexer rule to define a token as something inside a pair of ” (assuming the \” escape sequence is handled properly), because this would be considered as a string token erroneously:

/*  comment...."comment that looks */   /*like a string literal"...more comment */

In short, the 2 pairs /**/ and “” will interfere with one another because each can contain the start of the other as its valid content. So how should we define a lexer grammar to handle both cases?

  • 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. Editorial Team
    Editorial Team
    2026-05-25T19:19:18+00:00Added an answer on May 25, 2026 at 7:19 pm

    JavaMan wrote:

    I am trying to parse C++/Java style source files and would like to isolate comment, string literal, and whitespace as tokens.

    Shouldn’t you match char literals as well? Consider:

    char c = '"';
    

    The double quote should not be considered as the start of a string literal!

    JavaMan wrote:

    In short, the 2 pairs /**/ and “” will interfere with one another.

    Err, no. If a /* is “seen” first, it would consume all the way to the first */. For input like:

    /*  comment...."comment that looks like a string literal"...more comment */
    

    this would mean the double quotes are also consumed. The same for string literals: when a double quote is seen first, the /* and/or */ would be consumed until the next (un-escaped) " is encountered.

    Or did I misunderstand?

    Note that you can drop the options {greedy=false;}: from your grammar before .* or .+ which are by default ungreedy.

    Here’s a way:

    grammar T;
    
    parse
      :  (t=. 
           {
             if($t.type != OTHER) {
               System.out.printf("\%-10s >\%s<\n", tokenNames[$t.type], $t.text);
             }
           }
         )+
         EOF
      ;
    
    ML_COMMENT
      :  '/*' .* '*/'
      ;
    
    SL_COMMENT
      :  '//' ~('\r' | '\n')*
      ;
    
    STRING
      :  '"' (STR_ESC | ~('\\' | '"' | '\r' | '\n'))* '"'
      ;
    
    CHAR
      :  '\'' (CH_ESC | ~('\\' | '\'' | '\r' | '\n')) '\''
      ;
    
    SPACE
      :  (' ' | '\t' | '\r' | '\n')+
      ;
    
    OTHER
      :  . // fall-through rule: matches any char if none of the above matched
      ;
    
    fragment STR_ESC
      :  '\\' ('\\' | '"' | 't' | 'n' | 'r') // add more:  Unicode esapes, ...
      ;
    
    fragment CH_ESC
      :  '\\' ('\\' | '\'' | 't' | 'n' | 'r') // add more: Unicode esapes, Octal, ...
      ;
    

    which can be tested with:

    import org.antlr.runtime.*;
    
    public class Main {
      public static void main(String[] args) throws Exception {
        String source = 
            "String s = \" foo \\t /* bar */ baz\";\n" +
            "char c = '\"'; // comment /* here\n" +
            "/* multi \"no string\"\n" +
            "   line */";
        System.out.println(source + "\n-------------------------");
        TLexer lexer = new TLexer(new ANTLRStringStream(source));
        TParser parser = new TParser(new CommonTokenStream(lexer));
        parser.parse();
      }
    }
    

    If you run the class above, the following is printed to the console:

    String s = " foo \t /* bar */ baz";
    char c = '"'; // comment /* here
    /* multi "no string"
       line */
    -------------------------
    
    SPACE      > <
    SPACE      > <
    SPACE      > <
    STRING     >" foo \t /* bar */ baz"<
    SPACE      >
    <
    SPACE      > <
    SPACE      > <
    SPACE      > <
    CHAR       >'"'<
    SPACE      > <
    SL_COMMENT >// comment /* here<
    SPACE      >
    <
    ML_COMMENT >/* multi "no string"
       line */<
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Hi i am trying to parse a string into a java.sql.date Here is what
I have been trying to parse Java exceptions that appear in a log for
I'm trying to parse a webpage using Java with URLConnection. I try to set
Trying to parse an SQL string and pull out the parameters. Ex: select *
Im trying to parse the string located in /proc/stat in a linux filesystem using
I am trying to parse the following XML file in Java and to store
Preliminary: I am writting my own httpclient in Java. I am trying to parse
I am trying to parse a string which in JSON format only that keys
I was trying to parse the string: Portfolio1[{Exchange:NASDAQ-Symbol:INFY-Full Name:Infosys Technologies Limited (ADR)-Share Count:100.0-Percent Gain:388.2258065-The
I'm trying to parse a section of a large file with Java's Scanner library,

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.