简体   繁体   English

正则表达式匹配字符串并排除其他所有内容,直到换行

[英]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) 这个解决方案在某种程度上解决了我的问题,但是需要排除Ordernr之后的任何字符,直到回车(换行)

  1. 21Sid1 21Sid1
  2. Ordernr Ordernr
  3. E17222 E17222
  4. By 通过
  5. Seller 卖家

I am using ordernr[\\r\\n]+([^\\n\\r]+) to match ordernr and E17222 above. 我正在使用ordernr [\\ r \\ n] +([[^ \\ n \\ r] +)来匹配上述ordernrE17222 I want to do the same for the case below: 对于以下情况,我想做同样的事情:

  1. 21Sid1 21Sid1
  2. Ordernr Skip everything upto new line Ordernr跳过所有内容到新行
  3. E17222 E17222
  4. By 通过
  5. Seller 卖家

Basically exclude everything when Ordernr is found until a new line and grab the next line 找到Ordernr时,基本上将所有内容排除在外,直到出现新的一行并抓住下一行

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 (.*) . 由于.*匹配行终止符以外的所有内容,因此我们使用.*匹配新行之后匹配Ordernr之后的所有内容,然后使用新行,并再次使用(.*)捕获下一行的evrything。

Live demo here 现场演示在这里

Here's a sample code in Java: 这是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: OUTPUT:

group 1: E17222 第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. 在这里,我替换了点以匹配除换行以外的所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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