简体   繁体   English

仅在字符串的开头/结尾匹配正则表达式

[英]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.

相关问题 使用正则表达式匹配字符串的相同开始和结束字符 - Match the same start and end character of a string with Regex 正则表达式匹配字符串中的begin([)和end(,)(仅) - Regex to match beginning([) and and end(,) (only) in a string 正则表达式字符串开始/结束/中间一次匹配 - RegEx string start/end/middle one time match JavaScript RegEx:将不在字符串开头或结尾处的所有负号与货币输入匹配 - JavaScript RegEx: match all minuses that are not at start or end of string for currency input 正则表达式匹配没有开始和结束空格的字符串中的单词 - Regex match the words from a string without the start and end space Javascript REGEX仅用于删除字符串开头和结尾的字符,而不是中间的字符 - Javascript REGEX for deleting char only in string start and end, not in the middle 正则表达式以匹配URL-字符串末尾的数字,但也匹配字符串开头的字符 - Regex to match URL - number at end of string, but also match characters at start of string js regex从txt开始获取字符串,以“start”结尾,只有“end”结束一次 - js regex get string from txt start with “start” end with “end” only once 如何匹配字符串的开头和结尾? - How to match the start and end of a string? 正则表达式模式以匹配字符串的结尾 - regex pattern to match the end of a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM