简体   繁体   中英

Regex match for new lines

I am trying to get the log statements in my code using java. I am using this regex:

Log\.[dD].*\);

Test data:

Log.d(TAG, "Construct product info");

test test test test 

Log.d(TAG, "Loading Product Id: %d, Version: %s",
    productInfo.getProductId(),
    productInfo.getProductVersion());

test test test test 

Log.d(TAG, "Loading Product Id: " +
    ProductId + "Version:" +
    Version);

test test test test

for some reason, regex is only picking up 1st line which is

Log.d(TAG, "Construct product info");

Correct output should be:

Log.d(TAG, "Construct product info");

Log.d(TAG, "Loading Product Id: %d, Version: %s",
    productInfo.getProductId(),
    productInfo.getProductVersion());

Log.d(TAG, "Loading Product Id: " +
    ProductId + "Version:" +
    Version);

https://regex101.com/r/OCl9dy/3

If I am not mistaken, regex should return all Log.[dD] statements that ends with );

Please let me know why it does not pick up others and how to fix this.

thanks

This regex should work:

Log\.[dD][\s\S]*?\);

The two mistakes you made were:

  • . does not match line endings. You should use something similar to [\\s\\S] , which matches everything.
  • You need to match lazily , stop matching at the first ) you see. So write *? instead of * .

Note that the regex won't work for things like Log.d(TAG, "Construct (product); info"); because the first ); is not the end of the method call. To match these, I suggest you write/use a parser.

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM