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