如何对一个字符串进行编码以替换所有特殊字符

4

我有一个包含特殊字符的字符串。但是我必须将该字符串转换为不含任何特殊字符的字符串,所以我使用了Base64。但在Base64中,我们使用等号(=)符号,这是一个特殊字符。但我想将该字符串转换为仅具有字母数字字符的字符串。同时,我不能删除特殊字符,只需替换所有特殊字符以保持两个不同字符串之间的唯一性。如何实现这一点?哪种编码可以帮助我实现这个目标?

5个回答

3
最简单的选择是使用UTF-8将文本编码为二进制,然后将二进制转换为十六进制文本(每个字节两个字符)。这样做的效率不会很高,但它只包含字母数字字符。
你也可以使用base32来提高一些效率,但这可能需要更多的工作,除非你能找到一个支持base32的库。(支持十六进制编码的库非常常见。)

2
有许多种base64的变体,其中一些不使用填充。(仍然有两个非字母数字字符用于第62和63个字符。)
维基百科关于base64的页面详细介绍了“标准”变体,包括用于许多常见用例的变体。(您的是否与这些之一匹配?)
如果您的字符串必须严格为字母数字,则需要使用十六进制编码(一个字节变为2个十六进制数),或者自己编写编码方案。您所述的要求相当不寻常...

2

Commons codec 提供了一个URL安全版本的base64,它用 - 和 _ 替代 + 和 / 字符。

http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html#encodeBase64URLSafe(byte[])


2
最简单的方法是使用正则表达式来匹配所有非字母数字字符,并将它们替换为空字符串。
// This will remove all special characters except space.
var cleaned = stringToReplace.replace(/[^\w\s]/gm, '')

在上述正则表达式中添加任何特殊字符将跳过该字符。

// This will remove all special characters except space and period.
var cleaned = stringToReplace.replace(/[^\w\s.]/gm, '')

一个可运行的示例。
const regex = /[^\w\s]/gm;
const str = `This is a text with many special characters.
Hello, user, your password is 543#!\$32=!`;
const subst = ``;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

正则表达式解析。
[^\w\s]/gm
Match a single character not present in the list below [^\w\s]
\w matches any word character (equivalent to [a-zA-Z0-9_])
\s matches any whitespace character (equivalent to [\r\n\t\f\v \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff])

Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

1
链接似乎已经失效。 - Torsten Simon
1
@TorstenSimon 添加了另一个答案。 - Kannan Suresh

0
如果您确实只能使用字母数字字符,那么您将不得不想出一种转义方案,其中使用其中一个字符,例如使用0作为转义字符,然后将特殊字符编码为ASCII的2个字符十六进制编码。使用000表示0。
例如:
This is my special sentence with a 0.

编码为:

This020is020my020special020sentence020with020a02000002e

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接