用于匹配锚定否定和字符串的正则表达式
我尝试通过用另一个正则表达式替换正则表达式来在特定字符串(例如 Token
)之前添加一个空格: somethingToken
应该成为 something Token
但是某些令牌
应该保留 一些令牌_
而不是 something Token
(带有 2 个空格)
我无法找到一个与非空格字符匹配的正则表达式,然后是令牌,但在匹配中不包含非空格字符(否则它会得到也更换了)。 一次(失败的)尝试是尝试否定 \b
锚点(它应该与单词的开头匹配),但我不知道是否可以否定锚点。 对此的任何帮助表示赞赏。 谢谢。
I'm trying add a space before a particular string (Token
for example) by replacing a regex with another: somethingToken
should become something Token
but something Token
should staysomething Token_
and notsomething Token
(with 2 spaces)
I'm having trouble finding a regex that would match a non-space character and then the Token but without including the non-space character in the match (otherwise it would get replaced as well).
A (failed) attempt was to try to negate a \b
anchor (which should match the beginning of a word), but I don't know if I can negate an anchor.
Any help on this is appreciated.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我刚刚找到了这个问题的答案,也许对其他人有用:
它表示否定的单词边界,因此基本上匹配标准单词边界(\b)不匹配的地方。对于我的示例,它确实匹配 somethingToken 但不匹配 something Token ,后者保持原样。
I have just found the answer to this, perhaps it will be useful for someone else:
which represents a negated word boundary, so essentially matching wherever the standard word boundary (\b) does not match. For my example, it does indeed match somethingToken but not something Token which is left as is.
在Java中,这可以通过以下方式实现:
这里的概念是lookbehind和lookahead。有关详细信息,请参阅Regex 教程 - Lookahead 和 Lookbehind 零宽度断言。
In Java, this can be achieved as follows:
The concepts here are lookbehind and lookahead. See Regex Tutorial - Lookahead and Lookbehind zero-width assertions for more information.
(?
这将在后面查找非空格,然后向前查找 Token,但没有宽度。这样你就可以用空格替换这个匹配项。
编辑:如果你需要它在 Javascript 中工作,
\u0020?(?=令牌)
将空格设为可选,然后您将用空格替换该空格,而不会产生任何净变化。
(?<!\u0020)(?=Token)
This will look behind for a non-space, then will lookahead for Token, but have no width. This way you can replace this match with a space.
Edit: If you need it to work in Javascript,
\u0020?(?=Token)
Make a space optional, then you will replace the space with a space for no net change.