在分批可变除去非字母数字字符 [英] Removing non alphanumeric characters in a batch variable

查看:176
本文介绍了在分批可变除去非字母数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在批,我怎么会删除所有非字母(A-Z,A-Z,0-9,_)从一个字符变量?

In batch, how would I remove all non alphanumeric (a-z,A-Z,0-9,_) characters from a variable?

我是pretty知道我需要使用FINDSTR和一个正则表达式。

I'm pretty sure I need to use findstr and a regex.

推荐答案

的解对MC ND的作品,但它确实慢(需要〜1秒为小试样)。

The solutionof MC ND works, but it's really slow (Needs ~1second for the small test sample).

这是由回声造成了!_buf!| FINDSTR ... 结构,为每个角色管道造成的cmd.exe的两个实例,并启动 FINDSTR

This is caused by the echo "!_buf!"|findstr ... construct, as for each character the pipe creates two instances of cmd.exe and starts findstr.

但是,这也可以与纯的批次来解决。结果
如果是在地图中的每个字符进行测试变量

But this can be solved also with pure batch.
Each character is tested if it is in the map variable

:test

    set "_input=Th""i\s&& is not good _maybe_???"
    set "_output="
    set "map=abcdefghijklmnopqrstuvwxyz 1234567890"

:loop
if not defined _input goto endLoop    
for /F "delims=*~ eol=*" %%C in ("!_input:~0,1!") do (
    if "!map:%%C=!" NEQ "!map!" set "_output=!_output!%%C"
)
set "_input=!_input:~1!"
    goto loop

:endLoop
    echo(!_output!

和它可能是当转到环路解除加速。结果
然后,你需要先计算stringLength并用FOR / L循环每个字符然后循环。结果
这种解决方案比上述方法快〜6倍和〜40倍的MC ND的溶液快

And it could be speed up when the goto loop is removed.
Then you need to calculate the stringLength first and iterate then with a FOR/L loop over each character.
This solution is ~6 times faster than the above method and ~40 times faster than the solution of MC ND

set "_input=Th""i\s&& is not good _maybe_!~*???"
set "_output="
set "map=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890"
%$strLen% len _input

for /L %%n in (0 1 %len%) DO (
    for /F "delims=*~ eol=*" %%C in ("!_input:~%%n,1!") do (
        if "!map:%%C=!" NEQ "!map!" set "_output=!_output!%%C"
    )
)
exit /b

宏$ strlen的可以用

The macro $strlen can be defined with

set LF=^


::Above 2 blank lines are required - do not remove
@set ^"\n=^^^%LF%%LF%^%LF%%LF%^^":::: StrLen pResult pString
set $strLen=for /L %%n in (1 1 2) do if %%n==2 (%\n%
        for /F "tokens=1,2 delims=, " %%1 in ("!argv!") do (%\n%
            set "str=A!%%~2!"%\n%
              set "len=0"%\n%
              for /l %%A in (12,-1,0) do (%\n%
                set /a "len|=1<<%%A"%\n%
                for %%B in (!len!) do if "!str:~%%B,1!"=="" set /a "len&=~1<<%%A"%\n%
              )%\n%
              for %%v in (!len!) do endlocal^&if "%%~b" neq "" (set "%%~1=%%v") else echo %%v%\n%
        ) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,

这篇关于在分批可变除去非字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆