![](/img/trans.png)
[英]Can a regular expression match a character at the beginning OR end of the string (but not both)?
[英]Regular expression match any character at the beginning end with specific string
我有以下字符串:
"bar foo test-line drop-line"
我需要替换以任何东西开头并以“ -line”结尾的单词。
基本具有:
"bar foo new_word new_word"
我试过了:
string.replace(/\.-line$/g,'new_word')
但这不起作用。
尝试将此作为正则表达式:
/\S+-line(?![-\w])/
锚点一词在这里不合适,因为破折号不被认为是单词的一部分,因此/\\S+-line\\b/
会错误地匹配text-with-line-not-to-be-replaced
。 因此,先行构造。
当然,根据您的用例, \\S
可能看起来有些粗糙。 如果您的单词实际上只包含字母,然后是破折号等,那么您可以使用normal* (special normal*)*
模式:
/[a-z]+(-[a-z]+)*-line(?![-\w])/i
(正常: [az]
特殊: -
(编辑:感谢@ thg435更改了lookahead构造)
在正则表达式中,您可以使用\\ b来检测新单词的开头,并使用\\ w来表示“单词字符”:
"your string".replace(/\b\w+-line\b/g,'new_word')
怎么样
string.replace(/\b\S+-line\b/g,'new_word')
\\b
字边界
\\S
非空格
作为FGE敏锐地指出,我们需要一个\\b
后line
,所以我们不抓住事物结束lines
liner
等等等等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.