Bijin Abraham
Bijin Abraham

Reputation: 2177

Regex to match string from the back

Let's say we have a string "text\t1\nText that has to be extracted" what regex can be used so that we check the string from the back that is from the last " to n because the start of the string can change. In this case, I need to get only Text that has to be extracted. What generic regex can we use here?

I used this (?<=\\n1\\n)(.*)(?=“) but this will not work if the pattern before n changes to n2 or ntext.

Any help is appreciated.

Upvotes: 1

Views: 1701

Answers (3)

anubhava
anubhava

Reputation: 784958

You may use this regex:

/(?<=\\n)[^"\\]+(?="$)/

RegEx Demo

RegEx Details:

  • (?<=\\n): Lookbehind to make sure we have a \n before the current position
  • [^"\\]+: Match 1+ of any character that is not " and not \
  • (?="$): Make sure we have a " before line end ahead

Upvotes: 3

OnlineCop
OnlineCop

Reputation: 4069

/^(\d+)\n([^\n"]+)"$/ may have some edge cases, but will find the number (one or more digits), followed by a newline, followed by any character that is neither newline nor a double quote, followed by a literal double quote.

This would require that the double quote occurs immediately before the end-of-line (EOL), but if that's not required (for example, if you have a semi-colon after the closing quote), remove $ from the end.

Edit

Just noticed that it's the literal text \n and not a newline character.

/(?<=\\n)(\d+)\\n((?:[^\\"]+|\\.)*)"/

Regex101 example

Breakdown:

  • (?<=\\n) looks for a \ followed by the letter n.
  • (\d+) captures the 1-or-more digits.
  • \\n matches a literal \ followed by the letter n.
  • (...*) matches some text that repeats 0 or more times.
  • (?:...|...) matches any character that are neither a literal \ character nor a double quote character... OR a literal \ character that is followed by "anything" so you can have \n or \" etc. The entire group is matched repeatedly.
  • " at the end ensures that you're inside (well, we hope) a double-quoted string on the same line.

Upvotes: 1

JvdV
JvdV

Reputation: 75840

Can't you just split and take the last element?

var item = "text\n1\nText that has to be extracted";
var last = item.split(/\n/g).reverse()[0];
console.log(last) // "Text that has to be extracted"

Upvotes: 2

Related Questions