百分比编码保留字符

Posted

技术标签:

【中文标题】百分比编码保留字符【英文标题】:Percent Encoding Reserved Characters 【发布时间】:2021-10-10 15:28:40 【问题描述】:

Wikipedia 列出了我试图用百分比编码替换字符串中的几个保留字符。字符是:

Character Encoding
! %21
# %23
$ %24
% %25
& %26
' %27
( %28
) %29
* %2A
+ %2B
, %2C
/ %2F
: %3A
; %3B
= %3D
? %3F
@ %40
[ %5B
] %5D

我的批处理脚本正在读取用户的输入,然后输出一个字符串,其中保留字符已被其百分比编码值替换。

问题是某些字符没有被读入,而其他字符在尝试对它们进行百分比编码时不起作用。

我的代码是

@echo off
setlocal EnableDelayedExpansion
set /p pass=Enter pass: 

@REM Do % first so it doesn't replace all the new %
set "pass=!pass:%%=%%25!"

@REM Not working - set "pass=!pass:!=%%21!"
set "pass=!pass:#=%%23!"
set "pass=!pass:$=%%24!"
set "pass=!pass:&=%%26!"
set "pass=!pass:'=%%27!"
set "pass=!pass:(=%%28!"
set "pass=!pass:)=%%29!"
@REM Not working set "pass=!pass:*=%%2A!"
set "pass=!pass:+=%%2B!"
set "pass=!pass:,=%%2C!"
set "pass=!pass:/=%%2F!"
set "pass=!pass::=%%3A!"
set "pass=!pass:;=%%3B!"
@REM Not working set "pass=!pass:==%%3D!"
set "pass=!pass:?=%%3F!"
set "pass=!pass:@=%%40!"
set "pass=!pass:[=%%5B!"
set "pass=!pass:]=%%5D!"

echo %pass%
pause

我正在使用Test ! # $ % ' ( ) * + , / : ; = ? @ [ ] 进行测试。

文本中的! 似乎没有读入字符串,我不得不注释掉三个字符转换,因为它们不起作用。

我怎样才能让它读起来!在? 如何转义 3 个注释掉的字符,以便将所有保留字符转换为它们的百分比编码?

【问题讨论】:

echo(!pass!替换echo %pass% 【参考方案1】:

我会这样做:

@echo off
setlocal EnableDelayedExpansion

set /P "pass=Enter pass: "
echo !pass: =   !

rem Standard cases
for %%a in ("%%=25" "#=23" "$=24" "&=26" "'=27" "(=28" ")=29" "+=2B"
                    ",=2C" "/=2F" ":=3A" ";=3B" "@=40" "[=5B" "]=5D" ) do (
   for /F "tokens=1,2 delims== eol=" %%x in (%%a) do (
      set "pass=!pass:%%x=%%%%y!"
   )
)

rem First two special cases
setlocal DisableDelayedExpansion
set "pass=%pass:!=[21]%"
setlocal EnableDelayedExpansion
set "pass=!pass:[21]=%%21!"
set "pass=!pass:?=%%3F!"

rem Last two special cases
:star
for /F "tokens=1* delims=*" %%x in (" !pass! ") do (
   if "%%y" neq "" (
      set "pass=%%x%%2A%%y"
      set "pass=!pass:~1,-1!"
      goto star
   )
)
:equal
for /F "tokens=1* delims==" %%x in (" !pass! ") do (
   if "%%y" neq "" (
      set "pass=%%x%%3D%%y"
      set "pass=!pass:~1,-1!"
      goto equal
   )
)

echo %pass%

例子:

Enter pass: Test ! # $ % & ' ( ) * + , / : ; = ? @ [ ]
Test   !   #   $   %   &   '   (   )   *   +   ,   /   :   ;   =   ?   @   [   ]
Test %21 %23 %24 %25 %26 %27 %28 %29 %2A %2B %2C %2F %3A %3B %3D %3F %40 %5B %5D

【讨论】:

不错的一个!如果有两个连续的**==,会发生什么?

以上是关于百分比编码保留字符的主要内容,如果未能解决你的问题,请参考以下文章

如何在没有百分比编码的情况下在 Swift URL 中包含重音字符?

RFC3986 - 哪些 pchars 需要进行百分比编码?

urlbase64 编码规则

Jersey - servlet 上下文路径和/或 servlet 路径包含百分比编码的字符

如何对URL字符串进行百分号编码

对利率添加百分比,并保留几位小数