[英]Regular expression match any character at the beginning end with specific string
I have the following string: 我有以下字符串:
"bar foo test-line drop-line"
I need to replace the words that starts with anything and ends with '-line'. 我需要替换以任何东西开头并以“ -line”结尾的单词。
basically having: 基本具有:
"bar foo new_word new_word"
I tried: 我试过了:
string.replace(/\.-line$/g,'new_word')
but it doesn't work. 但这不起作用。
Try this as a regex: 尝试将此作为正则表达式:
/\S+-line(?![-\w])/
The word anchor is not suitable here since dashes are not considered part of a word, so /\\S+-line\\b/
would mistakenly match text-with-line-not-to-be-replaced
. 锚点一词在这里不合适,因为破折号不被认为是单词的一部分,因此/\\S+-line\\b/
会错误地匹配text-with-line-not-to-be-replaced
。 Hence the lookahead construct. 因此,先行构造。
Of course, according to your use case, \\S
may seem a little coarse. 当然,根据您的用例, \\S
可能看起来有些粗糙。 If your words really only consist of letters then dashes etc, then you can use the normal* (special normal*)*
pattern: 如果您的单词实际上只包含字母,然后是破折号等,那么您可以使用normal* (special normal*)*
模式:
/[a-z]+(-[a-z]+)*-line(?![-\w])/i
(normal: [az]
, special: -
) (正常: [az]
特殊: -
(edit: changed the lookahead construct, thanks to @thg435) (编辑:感谢@ thg435更改了lookahead构造)
In your regular expression, you can use \\b to detect beginning of new words and \\w for "word characters": 在正则表达式中,您可以使用\\ b来检测新单词的开头,并使用\\ w来表示“单词字符”:
"your string".replace(/\b\w+-line\b/g,'new_word')
See http://www.w3schools.com/jsref/jsref_obj_regexp.asp 参见http://www.w3schools.com/jsref/jsref_obj_regexp.asp
How about 怎么样
string.replace(/\b\S+-line\b/g,'new_word')
\\b
Word boundary \\b
字边界
\\S
non whitespace \\S
非空格
As fge astutely notes, we need a \\b
after line
so we don't catch things ending lines
liner
etc etc etc 作为FGE敏锐地指出,我们需要一个\\b
后line
,所以我们不抓住事物结束lines
liner
等等等等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.