1

I am using Pattern and Matcher classes from Java to parse a link file script. The text I need is in the SECTIONS part:

SECTIONS
    {
        .text : {} > FAST_MEM /* Link all .text sections into ROM */
        .intvecs : {} > 0x0 /* Link interrupt vectors at 0x0 */
        .data : /* Link .data sections */
        {
            tables.obj(.data)
            . = 0x400; /* Create hole at end of block */
        } = 0xFF00FF00 > EEPROM /* Fill and link into EEPROM */
        ctrl_vars: /* Create new ctrl_vars section */
        {
            ctrl.obj(.bss)
        } = 0x00000100 > SLOW_MEM /* Fill with 0x100 and link into RAM */
        .bss : {} > SLOW_MEM /* Link remaining .bss sections into RAM */
    }

right now I am using

Pattern SectPattern = Pattern.compile("(SECTIONS\\{(.*)\\})");

and I want to extract the (.*) group but the result is not what I expected Does anyone have any ideas of a better pattern to use?

2
  • so that means you might be having one or more SECTIONs in your file, correct? Commented Jun 17, 2012 at 7:56
  • Regular expressions are not the right choice for parsing matched, nestable braces. Commented Jun 17, 2012 at 8:27

2 Answers 2

1

This will match and print the content inside SECTIONS { and }.:

Pattern pattern = Pattern.compile("SECTIONS.*?\\{(.*)\\}", Pattern.DOTALL);
Matcher matcher = pattern.matcher(sample);
matcher.find();

System.out.println(matcher.group(1));

where sample is your pattern sample. Pattern.DOTALL is required to handle line breaks correctly, the others should be self-explanatory.

Sign up to request clarification or add additional context in comments.

Comments

0

Perhaps you have white spaces which you don't consider.
Try this:

"SECTIONS\\s*\\{(.*)\\}"

Notice that I also removed the outer group from the pattern (I don't see a reason for it).
In my example, after matching, use group 1.
Notice that this will work only if you do greedy matches (which is the case by default).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.