1

I have the following text below. How do I write the regex to capture all text related to REQ_XXX?

This is my expression .*(REQ_.*)\|, but it captures |3 |4 |5. I just want it to stop after the first | it sees.

enter image description here

2
  • I think you should delete and post in Stackoverflow.
    – johnny
    Sep 21, 2017 at 17:41
  • 3
    If we can answer it here, it should be fine. RegEx is perhaps a grey area between coding and application work. Sep 21, 2017 at 18:59

4 Answers 4

2

You can use :

.*(REQ_[^|]*)\|

The "|" character will be exclude.

1
2

Edit:

.*(REQ_.*?)\|

The trick is ? tells preceding .* to stop as early as possible. This way the first | that follows terminates the scope of .*. This is exactly what you want.

My old answer is below. It works well but I think the above is The Right Way.


Old answer:

.* matches (almost) everything, including |. Use [^|\n]* to match everything but | and newline.

.*(REQ_[^|]*)\|

\n is needed because pure [^|]* could span its match over multiple lines. I guess you don't want this.

1

Some of the solutions are already posted in other answers, I'm giving a summary here.

You can follow multiple approaches here, you need to decide based on your needs which one you use:

  1. give a positive list of characters appearing in your code:
    .*(REQ_[\w]+)[\s]*\|
    • in this case [\w]+ matches all word characters (letters, numbers and "_")
    • whitespaces before | are not included in your captured result ([\s]* is out of the brackets)
  2. give a negative list of characters, where you want your regex to stop:
    .*(REQ_[^|]+)\|
  3. use lazy match to stop at first possibility: .*(REQ_.+?)\|
0

If REQ_ is allways followed by word characters, you can simply use REQ_w+ or if you don't want to match ABCREQ_123, use a word boundary: \bREQ_\w+.

See in action

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .