[英]Match Regex Only at the Start/End of a String
As per the title, I'm trying to use a .match() function on a string to only match with instances that occur at the start or end of that string (but no where in the middle). 按照标题,我试图在字符串上使用.match()函数,使其仅与在该字符串的开头或结尾出现的实例(但中间没有位置)匹配。
For example, on the word "test": 例如,在单词“ test”上:
x = "1 TEST 1"
x1 = "TEST 1"
x2 = "1 TEST"
x3 = "TEST"
Only x1, x2 and x3 should match the regex. 只有x1,x2和x3应该与正则表达式匹配。 Currently, I have:
目前,我有:
.toUpperCase().match(/(TEST)/)
Which will match every instance of "test". 它将匹配每个“测试”实例。 I've tried using the ^ and $ modifiers, but they'll only match x3.
我试过使用^和$修饰符,但它们只能匹配x3。 This one however:`
然而,这一个:
.toUpperCase().match(/(TEST)$/)
Will match x2 and x3 only, with .toUpperCase().match(/^(TEST)/)
matching x1 and x3 only. 仅匹配x2和x3,
.toUpperCase().match(/^(TEST)/)
仅匹配x1和x3。
Just match one or the other using |
只需使用
|
匹配一个或另一个 . 。
.toUpperCase().match(/^TEST|TEST$/)
Also note that you don't need to put parentheses around TEST
. 另请注意,您不需要在
TEST
周围加上括号。
/^TEST.*|.*TEST$/
this regex will match a line if it starts or ends with "TEST". 此正则表达式将以“ TEST”开头或结尾匹配一行。 add
m
to match multiple lines 加
m
以匹配多行
Note: this regex will return the whole line 注意:此正则表达式将返回整行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.