[英]RegEx (in JavaScript find/replace) - match non-alphanumeric characters but ignore - and +
We have been using the following js/regex to find and replace all non-alphanumeric characters apart from - and + 我们一直在使用以下js / regex来查找和替换除 - 和+之外的所有非字母数字字符
outputString = outputString.replace(/[^\w|^\+|^-]*/g, "");
However it doesn't work entirely - it doesn't replace the ^ and | 但它并不完全有效 - 它不会取代^和| characters.
字符。 I can't help but wonder if this is something to do with the ^ and |
我不禁想知道这是否与^和|有关 being used as meta-characters in the regex itself.
在正则表达式本身中用作元字符。
I've tried switching to use [\\W|^+|^-]
, but that replaces the - and +. 我试过切换到使用
[\\W|^+|^-]
,但是它取代了 - 和+。 I thought that possibly a lookahead assertion may be the answer, but I'm not very sure how to implement them. 我认为可能是一个先行断言可能是答案,但我不太确定如何实现它们。
Has anyone got an idea how to accomplish this? 有没有人知道如何实现这一目标?
Character classes do not do alternation, hence why the |
字符类不做交替,因此为什么
|
is literal, and the ^
must be at the start of the class to take effect (otherwise it's treated literally.) 是文字的,并且
^
必须在类的开头才能生效(否则它将按字面意思处理。)
Use this: 用这个:
[^\w+-]+
(Also, if -
is not last, it needs to be escaped as \\-
inside a character class - so be careful if more characters might be added to the exception list). (另外,如果
-
不是最后一个,它需要在字符类中转义为\\-
- 因此如果可以将更多字符添加到例外列表中,请小心)。
You could also do it with a negative lookahead like this: 您也可以使用这样的负向前瞻:
(?![+-])\W
Note: You do not want a *
or +
after that \\W
, since the lookahead only applies to the immediately following character (and the g
flag makes the replace repeat until done). 注意:您不希望在
\\W
之后使用*
或+
,因为前瞻仅适用于紧随其后的字符(并且g
标志使替换重复直到完成)。
Also note that \\w
and \\W
consider _
as a word character. 另请注意
\\w
和\\W
将_
视为单词字符。 If that's not desired then to replace that you can use (?![+-])[\\W_]
(or use explicit ranges in the first expressions). 如果不需要那么替换你可以使用
(?![+-])[\\W_]
(或在第一个表达式中使用显式范围)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.