gauti
gauti

Reputation: 1274

how to extract previous string from matched string in regex in javascript?

I would extract a particular string from the matched string using regex.

IMP QuadroIMP QuadroIMP QuadroIMP QuadroIMP QuadroIMP Quadro IMP Quadrosdfsdfdsfsdfsd 0000022 DE BERNARDINIS FERNANDO DBRFNN72A03A515E 001468 03-01-1972 12-06-2006 IMP Quadro

from above para, I need to find where the date is available, upon that I need to extract 2nd and 3rd word from the matched string with single regular expression

".*\n(\d{2}-\d{2}-\d{4}) (\d{2}-\d{2}-\d{4})" - will result only 

"0000022 DE BERNARDINIS FERNANDO DBRFNN72A03A515E 001468
 03-01-1972 12-06-2006"

from the above string how to extract "DE BERNARDINIS" using any and condition in with the same regular expression

Upvotes: 3

Views: 67

Answers (1)

The fourth bird
The fourth bird

Reputation: 163477

For your example data, you might add matching 1+ digits from the start of the string, and then use 2 capturing groups to match the 2nd and the third word.

If there are not always digits at the start of the line, you could use ^\S+ to match 1+ times a non whitespace char instead of ^\d+

^\d+ (\w+) (\w+).*\n(\d{2}-\d{2}-\d{4}) (\d{2}-\d{2}-\d{4})
  • ^ Start of string
  • [0-9]+ (\w+) (\w+) Match 1+ digits, followed by matching 2 times a space and 1+ word chars
  • .*\n Match any char except a newline until the end of the line, then match a newline
  • (\d{2}-\d{2}-\d{4}) (\d{2}-\d{2}-\d{4}) 2 capturing groups matching your date like pattern

Regex demo

Upvotes: 2

Related Questions