Javascript regex: only matches end of text
I would like to find out multi-line texts ending in "Tr", "Br" and linebreak ("\ n") without the "_" character (none-whitespace and underscore). Exmples
Text 1:
Command1 Br
Command2 Tr
"Command1 Br \nCommand2 Tr " //match "Tr " at the end
Text 2:
Command3 con Tr
Command4 Br
"Command3 con Tr \nCommand4 Br " //match "Br " at the end
Text 3:
Command2 Tr
Command3 con Br
Command4 C_
"Command2 Tr \nCommand3 con Br \nCommand4 C_\n" //match "\n" at the end after C_
Text 4:
Command1 Tr
Command1 Br
Command2 Tr _
"Command1 Tr \nCommand1 Br \nCommand2 Tr _\n" //no match because of " _" preceded "\n"
Text 5:
Command1 Tr
Command1 Br
Command2 mt
"Command1 Tr \nCommand1 Br \nCommand2 mt\n" //match \n at the end after "mt"
Text 6:
Command2 ht
"\n\nCommand2 ht\n" //match \n at the end after "ht"
+3
source to share
1 answer
You can use the following regular expression to extract these matches:
/(?:^| [^_]|[^ ]_|[^ ][^_])([BT]r|\n)[\t ]*$/
See regex demo .
More details
-
(?:^| [^_]|[^ ]_|[^ ][^_])
- non-capturing group matching one of three alternatives:-
^
- beginning of line -
|
- or -
[^_]
- space and any char, but_
-
|
- or -
[^ ]_
- any char, but space and_
-
|
- or -
[^ ][^_]
- any char but space and then any char but_
(thus nospace
+_
)
-
-
([BT]r|\n)
- Capture Group 1: EitherBr
,Tr
or newline -
[\t ]*
- horizontal spaces 0+ (can be replaced with[^\S\r\n]
for better white space) -
$
- the very end of the line.
var ss = ["Command1 Br \nCommand2 Tr ", "Command3 con Tr \nCommand4 Br ", "Command2 Tr \nCommand3 con Br \nCommand4 C_\n",
"Command1 Tr \nCommand1 Br \nCommand2 Tr _\n", "Command1 Tr \nCommand1 Br \nCommand2 mt\n", "\n\nCommand2 ht\n"];
var rx = /(?:^| [^_]|[^ ]_|[^ ][^_])([BT]r|\n)[\t ]*$/;
for (var s of ss) {
console.log("Looking for a match in: " + s);
m = rx.exec(s);
if (m) {
console.log("Found: " + JSON.stringify(m[1], 0, 4));
} else {
console.log("No Match Found.");
}
}
+1
source to share