简体   繁体   中英

How to make a pattern using regex like below?

I would like to make a pattern.

For example, my input is

string str = "15-16-00-014716 AND15- [  ] (5) Description of 16-00-014715";

Expected output is

15-16-00-014716 AND15-16-00-014715

I tried below regex:

Regex.Replace(YourString, @"\s+\[.*(?=\b\d+)","");

But the output is like

15-16-00-014716 AND15-0-014715

You may use

Regex.Replace(str, @"\s+\[.*?(?=\b\d+(?:-|$))", "")

See the C# demo and the regex demo .

Regex graph:

在此输入图像描述

Main points:

  • .* should be non-greedy ( .*? matches as few any chars as possible)
  • (?:-|$) matches a - char or end of string position.

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