正则表达式必须以字母或数字开头,字符串只能包含字母,数字或斜杠,不能有双斜杠

时间:2015-02-24 23:57:54

标签: regex

我正在尝试检查一些字符串。以下是参数。

  1. 字符串必须以字母或数字开头
  2. 字符串只能包含字母,数字或斜杠
  3. 字符串不能有双斜杠(例如:“api // go”)
  4. Good Strings:

    go
    go2/api/hello
    go/api45
    

    Bad Strings:

    /go        (can't begin with a slash)
    go//api    (can't have a double slash)
    go/api%    (can't contain non number, letter or slash)
    

    我一直在尝试使用RegExr.com,但无济于事。我一直在尝试这个表达式:

    ^[^\/](([0-9A-Za-z])+(\/)?)+
    

    但它不太有用。

2 个答案:

答案 0 :(得分:3)

你可能会尝试这样的事情(我希望你所使用的任何风味都具有前瞻性!):

^(?!.*\/\/)[A-Za-z0-9][A-Za-z0-9\/]*$

有关完整说明和测试字符串,请参阅Regex 101 Demo

答案 1 :(得分:1)

你走了:

^[0-9a-z](\/?[0-9a-z])*\/?$

在当前表单中需要/i(不区分大小写的修饰符)。这非常简单,不需要前瞻。

说明:

^         Starts with
[0-9a-z]  1 Alphanumeric character
(         Start a repeatable group
\/?       Optional /
[0-9a-z]  1 Alphanumeric character
)*        Repeat the group zero or more times
\/?       Allow for an ending slash
$         String must end