批处理代码,用于测试脚本是否包含除字母和数字之外的任何内容

时间:2017-11-07 19:29:12

标签: string batch-file replace

我想知道是否可以测试变量以查看它是否包含除字母和数字之外的任何内容?我需要这个以限制用户名规格。我在下面有一个示例脚本。

 :top
echo enter a name
set /p name=">"
If contains (Anything other than letters/numbers/dashes) echo Invalid Name. & goto top
echo thank you!
pause

谢谢大家!

编辑:我认为这可能是重复的,但是我不知道要搜索什么来查找其他帖子...每当我搜索与我的问题相关的任何内容时,它都会在文本文件中找到并替换或其他不相干的东西。如果有人能找到重复,请告诉我,我将结束这个问题。谢谢。

2 个答案:

答案 0 :(得分:2)

这项工作适用于大多数ascii字符。它可能有一些警告。

Public arrBase

Private Sub Workbook_Open()
 Dim i As Integer
    ReDim arrBase(1 To Sheets.Count)
    For i = 1 To Sheets.Count
        arrBase(i) = ThisWorkbook.Sheets(i).Name
    Next
End Sub

Sub ActivateNewSheet()
    Dim i As Integer
    Dim found As Boolean

    For i = 1 To Sheets.Count
        found = Not IsInArray(Sheets(i).Name, arrBase)
        If found Then Sheets(i).Activate: Exit For
    Next

End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

答案 1 :(得分:2)

这只允许使用字母,数字和短划线:

@echo off & setlocal

:top
set /P "name="Enter a name: "
setlocal enabledelayedexpansion
echo(!name!| findstr /i "[^a-z0-9-]" >NUL && (
    endlocal
    set /P "=Invalid name. " <NUL
    goto top
)

endlocal
echo Thank you %name%!
pause