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 7780071
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T18:48:22+00:00 2026-06-01T18:48:22+00:00

I’ve got a Java program that goes through a file line by line, and

  • 0

I’ve got a Java program that goes through a file line by line, and tries to match each line against one of four regular expressions. Depending on which expression matched, the program performs a certain action. Here’s what I have:

private void processFile(ArrayList<String> lines) {
    ArrayList<Component> Components = new ArrayList<>();
    Pattern pattern = Pattern.compile(
            "Object name\\.{7}: (.++)|"
            + "\\{CAT=([^\\}]++)\\}|"
            + "\\{CODE=([^\\}]++)\\}|"
            + "\\{DESC=([^\\}]++)\\}");

    Matcher matcher;
    // Go through each line and see if the line matches the any of the regexes
    // defined
    Component currentComponent = null;

    for (String line : lines) {
        matcher = pattern.matcher(line);

        if (matcher.find()) {
            // We found a tag. Find out which one
            String match = matcher.group();

            if (match.startsWith("Obj")) {
                // We've got the object name
                if (currentComponent != null) {
                    Components.add(currentComponent);
                }
                currentComponent = new Component();
                currentComponent.setName(matcher.group(1));
            } else if (currentComponent != null) {
                if (match.startsWith("{CAT")) {
                    currentComponent.setCategory(matcher.group(2));
                } else if (match.startsWith("{CODE")) {
                    currentComponent.setOrderCode(matcher.group(3));
                } else if (match.startsWith("{DESC")) {
                    currentComponent.setDescription(matcher.group(4));
                }
            }
        }
    }

    if (currentComponent != null) {
        Components.add(currentComponent);
    }
}

As you can see, I’ve combined the four regular expressions into one and apply the whole regex on the line. If a match is found, I check the start of the string to determine which expression was matched and then extract the data from the group. In case anyone is interested in running the code, some sample data is presented below:

Object name.......: PMF3800SN
Last modified.....: Wednesday 9 November 2011 11:55:04 AM
File offset (hex).: 00140598 (Hex).
Checksum (hex)....: C1C0 (Hex).
Size (bytes)......: 1,736
Properties........: {*DEVICE}
                    {PREFIX=Q}
                    {*PROPDEFS}
                    {PACKAGE="PCB Package",PACKAGE,1,SOT-323 MOSFET}
                    {*INDEX}
                    {CAT=Transistors}
                    {SUBCAT=MOSFET}
                    {MFR=NXP}
                    {DESC=N-channel TrenchMOS standard level FET with ESD protection}
                    {CODE=1894711}
                    {*COMPONENT}

                    {PACKAGE=SOT-323 MOSFET}
                    *PINOUT SOT-323 MOSFET
                    {ELEMENTS=1}
                    {PIN "D" = D}
                    {PIN "G" = G}
                    {PIN "S" = S}

Although my code works, I don’t like the fact that I repeat part of the string later on when calling the startsWith routines.

I’m curious to see how others would have written this.

Amr

  • 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-06-01T18:48:23+00:00Added an answer on June 1, 2026 at 6:48 pm

    As @axtavt pointed out, you can discover directly whether a group participated in the match or not. You don’t even have to change the regex; you already have one capturing group for each alternative. I like to use the start(n) method for the tests because it seems neater, but checking group(n) for a null value (as @axtavt did) yields the same result. Here’s an example:

    private static void processFile(ArrayList<String> lines) {
    
        Pattern p = Pattern.compile(
                "Object name\\.{7}: (.++)|"
                + "\\{CAT=([^\\}]++)\\}|"
                + "\\{CODE=([^\\}]++)\\}|"
                + "\\{DESC=([^\\}]++)\\}");
    
        // Create the Matcher now and reassign it to each line as we go.
        Matcher m = p.matcher("");
    
        for (String line : lines) {
            if (m.reset(line).find()) {
                // If group #n participated in the match, start(n) will be non-negative.
                if (m.start(1) != -1) {
                    System.out.printf("%ncreating new component...%n");
                    System.out.printf("  name: %s%n", m.group(1));
                } else if (m.start(2) != -1) {
                    System.out.printf("  category: %s%n", m.group(2));
                } else if (m.start(3) != -1) {
                    System.out.printf("  order code: %s%n", m.group(3));
                } else if (m.start(4) != -1) {
                    System.out.printf("  description: %s%n", m.group(4));
                }
            }
        }
    }
    

    However, I’m not sure I agree with your reasoning about repeating part of the string in the code. If the data format changes, or you change which fields you extract, it seems like it would be easier to get out of sync when you update the code. In other words, your current code isn’t redundant, it’s self-documenting. 😀

    EDIT: You mentioned in a comment the possibility of processing the whole file at once instead of line by line. That’s actually the easier way:

    private static void processFile(String contents) {
    
        Pattern p = Pattern.compile(
                "Object name\\.{7}: (.++)|"
                + "\\{CAT=([^\\}]++)\\}|"
                + "\\{CODE=([^\\}]++)\\}|"
                + "\\{DESC=([^\\}]++)\\}");
    
        Matcher m = p.matcher(contents);
    
        while (m.find()) {
            if (m.start(1) != -1) {
                System.out.printf("%ncreating new component...%n");
                System.out.printf("  name: %s%n", m.group(1));
            } else if (m.start(2) != -1) {
                System.out.printf("  category: %s%n", m.group(2));
            } else if (m.start(3) != -1) {
                System.out.printf("  order code: %s%n", m.group(3));
            } else if (m.start(4) != -1) {
                System.out.printf("  description: %s%n", m.group(4));
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have just tried to save a simple *.rtf file with some websites and
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I have a French site that I want to parse, but am running into
I want use html5's new tag to play a wav file (currently only supported

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.