![](/img/trans.png)
[英]javascript how to regex match and replace on hashtags but exclude the hashtag character
[英]javascript regex exclude character
我有這樣的文字
AB:_c
答:_c
我正在使用的正則表達式是/:(.*)/g
,但它也捕獲了':_'
我想實現-> c
我所擁有的-> :_c
如何排除它們?
PS:用下划線代替空格 ,以便於理解。
編輯:我想捕獲':'后面的所有內容
EDIT2:這是帶有文本的regexr ,如您所見,它還捕獲了':'
您可以使用:/: /:\\s(.*)/g
.*)/ /:\\s(.*)/g
。
在開始捕獲之前,將在:
之后捕獲一個空格:
a b: c => "c"
a: c => "c"
var re = /:\\s(.*)/; var tests = [ 'a: c', 'a: cat', 'ba: test', 'a: c', 'Test: this is the rest of the sentence', ]; for (var i = 0; i < tests.length; i++) { console.log('TEST: ', '"' + tests[i] + '"'); console.log('RESULT: "' + tests[i].match(re)[1] + '"'); }
注意:您必須從比賽中獲得第一個捕獲組。 否則,您將無法獲得理想的結果。 請參閱如何在JavaScript正則表達式中訪問匹配的組? 有關如何執行此操作的信息。
如果您知道下划線將始終為c
前綴,則可以執行以下操作:/: /:_?(.*)/g
_?
匹配0或1下划線,因此結果只能是c
。
console.log('ab:_c'.match(/:_?(.*)/)[1])
是否要獲取字符串“ c”或最后一個字符?
var a = "a:_c a b:_c";
/c/g.exec(a)
/.$/g.exec(a)
編輯以匹配評論:
使用以下命令刪除“:_”之前的所有內容,包括“:_”
a.replace(/.*:_*/, '')
對於空間:
a.replace(/.*:\s*/, '')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.