簡體   English   中英

Javascript RegEx:捕獲-A,但不捕獲AA。 其中A是集合[A-Za-z]中的任何字母。 破折號后跟字母通行證,破折號被字母包圍

[英]Javascript RegEx: capture -A but not A-A. where A is any letter in the set [A-Za-z]. dash followed by letter passes, dash surrounded by letters doesnt

示例: let stringTest = "-this -andthis but-not-this"

// match = ['-this', '-andthis']並忽略“ but-not-this”

所以我想捕捉-[A-Za-z]+

這是我忽略AA情況的嘗試: [^([A-Za-z]-[A-Za-z])]

我認為這匹配任何東西,除了任何字母后跟破折號和任何字母。

它不能按預期工作(否定集中存在嵌套字符集的問題?),我也不知道如何將其與匹配-A的表達式結合使用

這可能嗎? 我的困惑的一部分是了解如何在否定字符集中嵌套字符集和/或字符組[^ignoreStuffHere]

提前致謝

可能有助於解釋原因:

我正在接收包含“標志”“數據”對的字符串,其中標志為-flag且與該標志關聯的數據為以下非標志字符/單詞

例如

-flag1 data1 data1 can be long -flag2 data2 -flag3 data3-has dashes in it but isnt a flag

我試圖將其拆分並存儲為標志+數據子字符串

const pairsArray = arguments.slice(arguments.indexOf('-'))
        .replace(/(\ -)/g, '-')
        .split(/-/g)
        .splice(1);

上面示例中的pairsArray應該如下所示:

pairsArray = ['flag1 data1 data1 can be long',
 'flag2 data2',
 'flag3 data3-has dashes in it but isnt a flag' 
]

相反,它正在考慮每個破折號周圍都包含字母(帶有破折號的數據,而不是標志),並將其拆分

pairsArray = ['flag1 data1 data1 can be long',
 'flag2 data2',
 'flag3 data3',
 '-has dashes in it but isnt a flag' 
]

怎么樣?

 let stringTest = "-this -andthis but-not-this"; console.log( stringTest.match(/(?:^| )-[A-Za-z]+/g).map(s => s.trim()) ) 

對於更新后的情況,您可以嘗試在空格后面加上破折號的方式進行split

 var stringTest = "-flag1 data1 data1 can be long -flag2 data2 -flag3 data3-has dashes in it but isnt a flag" console.log( stringTest.split(/ (?=-)/) ) // if you don't want to keep the dash at all console.log( stringTest.split(/ -/).map(s => s.replace(/^-/, "")) ) 

暫無
暫無

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

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