Ali
Ali

Reputation: 8100

Find and Replace a pattern using Java RegEx in block comments

This is the regex which is used to find block comments and it works absolutely fine

/\\*(?>(?:(?>[^*]+)|\\*(?!/))*)\\*/

I just need to modify it a little bit. Find a semi-colon (;) that "may" exists in the block comments and replace it with a white space.

Currently I am doing this

while (m.find()) {
    if (m.group().contains(";")) {
        replacement = m.group().replaceAll(";", "");
        m.appendReplacement(sb, replacement);
    }
}
m.appendTail(sb);

But I need to replace it with a str.replaceAll kind of statement. In short anything that is more efficient because I get out of memory exception. I fixed a few other regex that used to throw same exception and they are working fine. I hope this regex can also be optimized.

--- Edit ---

These are the string you can test this regex on

/* this* is a ;*comment ; */

/* This ; is* 
another
;*block
comment;
;*/

Thanks

Upvotes: 0

Views: 1206

Answers (2)

temple.t
temple.t

Reputation: 39

It'l be much simper to use (?s)/\*.+?\*/ regexp. In your expression you use negative lookahead that "eat" your memory. And your code may be simpler:

while (m.find()) {
    m.appendReplacement(sb, m.group().replace(";","");
}
m.appendTail(sb);

Upvotes: 3

itun
itun

Reputation: 3521

There are two variants(try both):

1). Why are you using ?>? I don't know what it means and I don't see a need to use something special here like ?>. Change it to ?:.

2). Your loop is infinite. You need this:

    int index = 0;
    while (m.find(index)) {
        if (m.group().contains(";")) {
            replacement = m.group().replaceAll(";", "");
            m.appendReplacement(sb, replacement);
        }
        index = m.end();
    }

Upvotes: 0

Related Questions