簡體   English   中英

PCRE模式數字的正則表達式,后跟任意數量的數字和正斜杠,沒有以數字結尾的雙斜杠嗎?

[英]PCRE Patterns Regular Expression for Digit Followed by any number of digits and forwards slashes no double slashes ending with digit?

到目前為止,我有以下內容:

'#^[0-9]([0-9]|/)*$[0-9]#'

我使用#作為定界符,因為模式中使用正斜杠。

但是它不能正常工作,它需要以一個數字開頭,並包含數字和斜杠(沒有雙斜杠),並以一個數字結尾。

我忘記了如何更改定界符。 使用某些命令/語言,您必須在開始時像這樣的\\#開頭,使用#作為分隔符。 對於您來說可能並非如此。

我可能應該先查詢我的RE。 但這是一個誠實的挑戰。

'#^[0-9][0-9/[^(//)]]+[0-9]$#'    //greedy


'#^[0-9][0-9/[^(//)]]+?[0-9]$#'   //non-greedy

您可以使用以下簡單的正則表達式( 在線演示向您顯示哪些字符串匹配或失敗):

^\d(?:(?!//)[\d/])+\d$

代碼樣例

$regex = "~^\d(?:(?!//)[\d/])+\d$~";
if(preg_match($regex,$string,$m)) echo $m[0];

解釋正則表達式

^                        # the beginning of the string
\d                       # digits (0-9)
(?:                      # group, but do not capture (1 or more times
                         # (matching the most amount possible)):
  (?!                    #   look ahead to see if there is not:
    //                   #     '//'
  )                      #   end of look-ahead
  [\d/]                  #   any character of: digits (0-9), '/'
)+                       # end of grouping
\d                       # digits (0-9)
$                        # before an optional \n, and the end of the
                         # string

我的解決方案:

'#^[0-9]+(/[0-9]+)*$#'

編輯如果必須存在至少一個斜杠:

'#^[0-9]+(/[0-9]+)+$#'

或帶有非收集括號和\\d而不是[0-9]

'#^\d+(?:/\d+)*$#'

您應該使用這樣的東西:

%^\d+(?:/\d+)+$%usD

說明:

%               # beginning of the pattern
    ^           # beginning of the string
        \d+     # it starts with at least one digit
        (?:     # beginning of a non-capturing group which contains
            /   # a single slash
            \d+ # followed by at least one digit, so it will never match double slashes
        )       # end of non-capturing group
        +       # the non-capturing group should match once or more
    $           # end of the string
%               # end of the pattern
    u           # unicode string
    s           # the "." matches all characters including "\n"
    D           # the "$" matches the end of the string and not "\n" (end of the line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM