简体   繁体   中英

Regex to match a string and exclude everything else until a new line

This solution somewhat solves my issue but need to exclude any characters after Ordernr until a carriage return(new line)

  1. 21Sid1
  2. Ordernr
  3. E17222
  4. By
  5. Seller

I am using ordernr[\\r\\n]+([^\\n\\r]+) to match ordernr and E17222 above. I want to do the same for the case below:

  1. 21Sid1
  2. Ordernr Skip everything upto new line
  3. E17222
  4. By
  5. Seller

Basically exclude everything when Ordernr is found until a new line and grab the next line

This should do:

/Ordernr.*[\\r\\n]+(.*)/g

Since, .* matches everything except line terminators, so we're matching everything after Ordernr except new line using .* then a new line and again we capture evrything on the next line using (.*) .

Live demo here

Here's a sample code in Java:

String line = "21Sid1\nOrdernr Skip everything upto new line\nE17222\nBy\nSeller";
Pattern pattern = Pattern.compile("Ordernr.*[\r\n]+(.*)");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
    System.out.println("group 1: " + matcher.group(1));
}else{
    System.out.println("No match found");
}

OUTPUT:

group 1: E17222

Check the result here .

EDIT

To make this regex work with your dot matches all consraint, try this:

/Ordernr[^\n\r]*[\r\n]+([^\n\r]*)/g

here I've replaced dot to match everything except new lines.

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