Javascript 正则表达式:捕获 -A 但不是 A-A。其中 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]+

这是我试图忽略 A-A 情况的尝试: [^([A-Za-z]-[A-Za-z])]

我认为这可以匹配除任何字母后跟破折号后跟任何字母以外的任何内容。

它没有按预期工作(在否定集中嵌套字符集有问题?)我也不知道如何将它与匹配的表达式组合 -A

这可能吗?我的部分困惑在于理解如何在否定字符集 [^ignoreStuffHere]

中嵌套字符集 and/or 字符组

提前致谢

这可能有助于解释原因:

我收到的字符串包含 "flag" "data" 对 其中标志是 -flag,与该标志关联的数据是以下非标志 characters/words

例如

-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())
)

对于更新后的案例,您可以在 space 上尝试 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(/^-/, ""))
)