簡體   English   中英

正則表達式專門匹配@ first.last格式,之前或之后均不匹配

[英]Regex to specifically match @first.last format and nothing before or after

我有一個格式為some words @first.last more words @first.last的字符串some words @first.last more words @first.last 我想編寫一個正則表達式以選擇格式為@first.last任何子字符串,以便可以用其他內容替換該子字符串。 此正則表達式僅應考慮@first.last子字符串,並忽略@符號前面的任何字符或last一個空格(包括該空格)之后的第一個空格之后的任何字符。 例如:

regex = new RegExp(/[^\[\s](@[a-zA-Z0-9\.\-]+)/im);
str = 'Hey @first.last tell [@first.last] to check this out';
str = str.replace(regex, 'Keanu');
/** str: 'Hey Keanu tell [@first.last] to check this out? **?

我嘗試過的正則表達式:

  • (@[a-zA-Z0-9\\.\\-]+) ->將使我成為其中的一部分,但不會刪除@符號前的字符

  • [^\\[](@[a-zA-Z0-9\\.\\-]+) ->如果@first.last是字符串的第一個子字符串,即此正則表達式將失敗。 @first.last look at this不會被str.replace調用更改

  • [^\\[\\s](@[a-zA-Z0-9\\.\\-]+) ->嘗試過濾掉前導空格

  • [^.+?](@[a-zA-Z0-9\\.\\-]+)

使我絆倒​​的主要是在(@[a-zA-Z0-9\\.\\-]+) ,以確保我僅檢測到@符號以及緊隨其后的字符。最后一種格式。

感謝您的幫助和協助。

使用像[a-zA-Z0-9.-]+這樣的字符類有點廣泛,因為它不能保證例如點不位於結尾。 它可以匹配任何列出的內容,例如--.--也有效。 請注意,您不必逃脫點,也不必逃脫破折號,如果它在末尾。

  1. 一個模式 (@[a-zA-Z0-9\\.\\-]+)兩者都匹配,因為左右兩側沒有設置邊界。

  2. 第二個模式 [^\\[](@[a-zA-Z0-9\\.\\-]+)匹配,包括前導空格,因為它與否定的字符類[^\\[]匹配,但不匹配[

  3. 第三個模式 [^\\[\\s](@[a-zA-Z0-9\\.\\-]+)不匹配,因為現在取反的字符類[^\\[\\s]不允許與前導匹配空間。

  4. 第四個模式 [^.+?](@[a-zA-Z0-9\\.\\-]+)匹配前導[因為它與不匹配a的[^.+?]匹配. +?

您可以使用一個捕獲組,其中該組可以匹配字符串的開頭或空白char,然后將@部分與單詞char和一個點匹配:

(^|\s)@\w+\.\w+(?!\S)

說明

  • (^|\\s)捕獲組1,字符串或空白字符的開頭
  • @\\w+\\.\\w+匹配@ ,然后是1+個字符,一個點和1+個字符(您也可以使用[a-zA-Z0-9]代替\\w
  • (?!\\S)斷言直接在右邊的不是非空格字符

在替換中,使用替換后的第一個捕獲組$1Keanu

正則表達式演示

 regex = /(^|\\s)@\\w+\\.\\w+(?!\\S)/g; str = 'Hey @first.last tell [@first.last] to check this out'; str = str.replace(regex, "$1Keanu"); console.log(str); 

我的猜測是,這種表達方式也許也可以在這里使用,

(\s+|^)(@[a-z0-9-]+\.[a-z0-9-]+)(\s+|$)

\\s+是為了防止出現其他空格,如果需要的話,我們可以簡單地修改char類。

 const regex = /(\\s+|^)(@[a-z0-9-]+\\.[a-z0-9-]+)(\\s+|$)/gis; const str = `some words @first.last more words @first.last some words @first.last more words @first.last012 some other text some words @first.last more words @first.last012\\$%^& some words@first.last more words@first.last`; const subst = `$1Keanu$3`; const result = str.replace(regex, subst); console.log(result); 

請參閱演示以獲取解釋和更多信息。

RegEx電路

jex.im可視化正則表達式:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM