正則表達式:如何在匹配的字符串之前刪除字符?

[英]Regex: How do I remove the character BEFORE the matched string?


I am intercepting messages which contain the following characters:

我攔截包含以下字符的郵件:

*_-

However, whenever any one of these characters comes through, it will always be preceded by a \. The \ is just for formatting though and I want to remove it before sending it off to my server. I know how to easily create a regex which would remove this backslash from a single letter:

但是,每當這些角色中的任何一個出現時,它始終會以\開頭。 \只是用於格式化,我想在將其發送到我的服務器之前將其刪除。我知道如何輕松創建一個正則表達式,從單個字母中刪除這個反斜杠:

'omg\_bbq\_everywhere'.replace(/\\_/g, '')

And I recognize I could just do this operation 3 times: once for each character I want to remove the preceding backslash for. But how can I create a single regex which would detect all three characters and remove the preceding backslash in all 3 cases?

而且我知道我可以執行此操作3次:每個字符一次,我想刪除前面的反斜杠。但是,我怎樣才能創建一個單一的正則表達式來檢測所有三個字符並在所有3個案例中刪除前面的反斜杠?

2 个解决方案

#1


3  

You can use a character class like [*_-].

您可以使用像[* _-]這樣的字符類。

To remove only the backslash before these characters:

要僅刪除這些字符前的反斜杠:

document.body.innerHTML =
   "omg\\-bbq\\*everywhere\\-".replace(/\\([*_-])/g, '$1');

When you place a subpattern into a capturing group ((...)), you capture that subtext into a numbered buffer, and then you can reference it with a $1 backreference (1 because there is only one (...) in the pattern.)

將子模式放入捕獲組((...))時,將該子文本捕獲到編號緩沖區中,然后可以使用$ 1反向引用(1,因為只有一個(...))模式。)

#2


1  

This is a good time to use atomic matching. Specifically you want to check for the slash and then positive lookahead for any of those characters.

這是使用原子匹配的好時機。具體來說,您要檢查斜杠,然后檢查任何這些字符的正向前瞻。

Ignoring the code, the raw regex you want is:

忽略代碼,你想要的原始正則表達式是:

\\(?=[*_-])

\\(?= [* _-])

A literal backslash, with one of these characters in front of it: *_-

一個字面反斜杠,前面有一個這樣的字符:* _-

So now you are matching the slash. The atomic match is a 0 length match, so it doesn't match anything, but sets a requirement that "for this to be a valid match, it needs to be followed by [*_-]"

所以現在你匹配斜線。原子匹配是一個0​​長度匹配,所以它不匹配任何東西,但設置一個要求“為了這是一個有效的匹配,它需要后跟[* _-]”

Atomic groups: http://www.regular-expressions.info/atomic.html

原子團:http://www.regular-expressions.info/atomic.html

Lookaround statements: http://www.regular-expressions.info/lookaround.html

外觀陳述:http://www.regular-expressions.info/lookaround.html

Positive and negative lookahead and lookbehind matches are available.

可以使用正面和負面的前瞻和后仰比賽。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/02/05/c3f25d7a085c85f8e23d4e37c4932010.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com