Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect end of line or end of string with Javascript regex

I'm trying to find the Javascript regex to detect a keyword (any character) followed by either new line or end of string. This is my attempt:

.+(?:\n|$)

I'm not sure that the $ can be used in the or condition. Any thoughts?

UPDATE

What I am trying to detect with the regex is a keyword follow by either (1) another keyword, or (2) nothing (therefore new line or end of string)

For example: the string "aaa" right before the new line it would be a match; the string "bbb" at the end of the string it would be a match as well.

like image 485
ps0604 Avatar asked May 15 '15 00:05

ps0604


People also ask

How do you specify the end of a line in regex?

End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.

What is the regex pattern for end of string?

The correct regex to use is ^\d+$. Because “start of string” must be matched before the match of \d+, and “end of string” must be matched right after it, the entire string must consist of digits for ^\d+$ to be able to match.

How do you match the end of a string?

To match the start or the end of a line, we use the following anchors: Caret (^) matches the position before the first character in the string. Dollar ($) matches the position right after the last character in the string.

What is G at end of regex?

RegExp. prototype. global has the value true if the g flag was used; otherwise, false . The g flag indicates that the regular expression should be tested against all possible matches in a string.


1 Answers

Here you go: https://regex101.com/r/tP5eV8/2

/[a-z]+$/gm

g returns multiple matches and m is for multi line
$ matches new line

This only matches the last keyword of the line. Here is one that matches one or several words separated by space and ending in a newline: https://regex101.com/r/zB9bS0/1

(?:(?: |^)([a-z]+))+$
like image 72
Björn Nilsson Avatar answered Oct 26 '22 20:10

Björn Nilsson