[英]Regex matching a string pattern and number ( url format )
我有一個遵循此網址格式的字符串
https://www.examples.org/activity-group/8712/activity/202803
// note : the end ending of the url can be different
https://www.examples.org/activity-group/8712/activity/202803?ref=bla
https://www.examples.org/activity-group/8712/activity/202803/something
我正在嘗試寫一個匹配的正則表達式
https://www.examples.org/activity-group/{number}/activity/{number}*
其中{number}是長度為1到10的整數。
如何定義一個正則表達式來檢查字符串模式並檢查數字是否在字符串的正確位置?
背景:在Google表單中,為了驗證答案,我想強制人們以這種格式輸入網址。 因此使用此正則表達式。
對於與該格式不匹配的Urls,正則表達式應返回false。 例如: https : //www.notthesite.org/group/8712/activity/astring
我看了幾個示例,但是只有字符串中存在數字時它們才匹配。
示例來源:
^https:\\/\\/www\\.examples\\.org\\/activity-group\\/[0-9]{1,10}\\/activity\\/[0-9]{1,10}(\\/[az]+)*((\\?[az]+=[a-zA-Z0-9]+)(\\&[az]+=[a-zA-Z0-9]+)*)*$
^
-字符串開頭 \\
-轉義字符 [0-9]
-一個數字 {1,10}
-上一項至十項之間 (\\/[az]+)*
-允許其他URL段 ((\\?[az]+=[a-zA-Z0-9]+)(\\&[az]+=[a-zA-Z0-9]+)*)*
-允許使用第一個參數查詢參數一個?
以及其他所有使用&
$
-字符串結尾 這是假定URL段和查詢參數鍵僅是小寫字母。 查詢參數值可以是小寫字母,大寫字母或數字。
你可以用
https?:\/\/(?:[^/]+\/){2}(\d+)\/[^/]+\/(\d+)
參見regex101.com上的演示 。
https?:\\/\\/ # http:// or https:// (?:[^/]+\\/){2} # not "/", followed by "/", twice (\\d+) # 1+ digits \\/[^/]+\\/ # same pattern as above (\\d+) # the other number
您需要分別使用組1
和2
。
https:\\/\\/[^/]+\\/activity-group\\/(\\d+)\\/activity\\/(\\d+)
哪個讀
https:\\/\\/[^/]+ # https:// + some domain name \\/activity-group\\/ # /activity-group/ (\\d+) # first number \\/activity\\/ # /activity/ (\\d+) # second number
在regex101.com上查看另一個演示 。
可能您需要類似:
(http[s]?:\/\/)?www.examples.org\/activity-group\/(\d{1,10})\/activity\/(\d{1,10})([\S]+?)$
哪里:
(http[s]?:\\/\\/)?
匹配任何http://或https://部分。 www.examples.org
是您的域名。 (\\d{1,10})
將匹配最大len為10(在activity-group之后 )的第一個整數。 (\\d{1,10})
將匹配activity之后的第二個整數。 ([\\S]+?)$
將與第二個數字之后的所有可選數據匹配,直到找到新行為止,並假設您在\\m
使用多行標志。 希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.