Regex捕获空格和特殊字符,除了单词中的连字符

Javascript: Regex to capture white space and special characters EXCEPT hyphens within words

本文关键字:单词中 连字符 特殊字符 空格 Regex      更新时间:2023-09-26

目前使用/['W]+/g得到我所有非单词字符,这是我想要的。

但是,我想省略连字符,当它们没有被空格包围时(也就是说,当它们被用作连接词时)。

例子:

 var test = [
    'e-mail', // Nothing  shouldn't be captured
    'e-commerce is great.', // Spaces and full stop should be captured
    'He - yes he - went', // Dashes and white space should be captured
    'He&-you, me-him' // &-, and the whitespace should be captured while the dash in me-him should not
    ]

尝试使用(['W]-|-['W]|[^'w-])+

在正则表达式中的否定是繁琐的,通常你必须使用查找来解决问题,但这里有一个简单的修复。我没有匹配所有的非单词字符(['W]),而是匹配了所有不是单词字符或连字符([^'w-])的字符,然后添加了连字符是而不是被字符包围的特殊情况(['W]--['W])。我必须先放置连字符捕获,否则非单词、非连字符捕获将匹配两个空格或特殊字符,而下一部分将无法拾取连字符。