PLB
PLB

Reputation: 891

Regex to search for two consecutive lines if the second doesn't start with a given word

I am trying (in Eclipse, I don't know if the syntax is different there) to write a regex that will select everything from 'service' up to the next two ';', but skipping the search if between the two ';' there is the word 'assert'.

This means that in the following example, I would like to select the text 'service.updateBasket.........test();' and not the text 'service.createBasket.........asserThat.....;'

BasketBean updateBasketRepsonse =
   service.updateBasket(login.getSessionId(),
                        Identity.valueOf(createdbasketBean.getGeneralID()),
                        basketSaveRequestBean);

test();

Response createBasketResponse = service.createBasket(login.getSessionId(),
                                                     basketSaveRequestBean);

assertThat(createBasketResponse).hasStatus(Status.CREATED);

So far I've written the regex service\.(.*\R)*?.*;, which finds the text I want till the first ';'. But I am having problem in handling the search till the next ';'.

For example service\.(.*\R)*?.*;\R.*; sometimes goes up to the third ';' (if there is an empty line after the first ';')... and I don't understand why.

Especially, I can't seem to find a way to skip the search if the line after the first ';' starts with 'assertThat' - that would be my final goal.

Note that the lines I am searching for are CONSECUTIVE, i.e. that the search only has to consider lines where the first ';' is followed by a line with text... as mentioned above, I am having troubles with that too :(

Upvotes: 1

Views: 389

Answers (2)

lilactiger89
lilactiger89

Reputation: 2518

For example service\.(.*\R)*?.*;\R.*; sometimes goes up to the third ';' (if there is an empty line after the first ';')... and I don't understand why.

I think that you are missing only a small part off of the end of your expression try

service\.(.*\R)*?.*;\R.*?;

The final ? makes the last part of the expression lazy which means that it should only go up to the second ;

Upvotes: 0

Ωmega
Ωmega

Reputation: 43683

service(?![^;]*;[^;]*assert[^;]*;)[^;]*;[^;]*;

See this demo.


EDIT:

To prevent empty lines to be a part of match, use more complex pattern

service(?!(?:[^;\n\r]|[\n\r](?![\n\r]))*;(?:[^;\n\r]|[\n\r](?![\n\r]))*assert(?:[^;\n\r]|[\n\r](?![\n\r]))*;)(?:[^;\n\r]|[\n\r](?![\n\r]))*;(?:[^;\n\r]|[\n\r](?![\n\r]))*;

See this demo.

Upvotes: 1

Related Questions