[英]RegEx to find a PHP RegEx string
我想匹配一個PHP正則表達式字符串。
據我所知,它們總是采用格式(如果我錯了,請糾正我):
/ One opening forward slash
the expression Any regular expression
/ One closing forward slash
[imsxe] Any number of the modifiers NOT REPEATING
我對此的表達是:
^/.+/[imsxe]{0,5}$
作為PHP字符串編寫的(帶有打開/關閉正斜杠和轉義的內部正斜杠)是這樣的:
$regex = '/^\/.+\/[imsxe]{0,5}$/';
這是:
^ From the beginning
/ Literal forward slash
.+ Any character, one or more
/ Literal forward slash
[imsxe]{0,5} Any of the chars i,m,s,x,e, 0-5 times (only 5 to choose from)
$ Until the end
這有效,但是它允許重復修飾符,即:
This: ^/.+/[imsxe]{0,5}$
Allows this: '/blah/ii'
Allows this: '/blah/eee'
Allows this: '/blah/eise'
etc...
什么時候不應該。
我個人使用RegexPal進行測試,因為它免費且簡單。
如果(為了幫助我)您想這樣做,請單擊上方的鏈接(或訪問http://regexpal.com ),然后將我的表達式粘貼到頂部文本框中
^/.+/[imsxe]{0,5}$
然后將我的測試粘貼到底部的文本框中
/^[0-9]+$/i
/^[0-9]+$/m
/^[0-9]+$/s
/^[0-9]+$/x
/^[0-9]+$/e
/^[0-9]+$/ii
/^[0-9]+$/mm
/^[0-9]+$/ss
/^[0-9]+$/xx
/^[0-9]+$/ee
/^[0-9]+$/iei
/^[0-9]+$/mim
/^[0-9]+$/sis
/^[0-9]+$/xix
/^[0-9]+$/eie
確保單擊頂部第二個復選框,其中顯示“ ^ $匹配換行符(m)”以啟用多行測試。
謝謝您的幫助
閱讀有關Regex的評論后,它們通常具有不同的分隔符,即
/[0-9]+/ == #[0-9]+#
這不是問題,可以考慮到我的正則表達式解決方案中。
我真正需要知道的是如何防止重復字符!
需要這樣的功能很簡單...
我正在使用Eric Hynds編寫的jQuery UI MultiSelect Widget 。
在這里找到簡單的演示
現在,在我的應用程序中,我正在擴展插件,以便將某些選項懸停在右側時會彈出一個小菜單。 彈出的菜單可以是任何html元素。
我希望多個選項能夠顯示相同的元素。 所以我的API是這樣的:
$('#select_element_id')
// Erics MultiSelect API
.multiselect({
// MultiSelect options
})
// My API
.multiselect_side_pane({
menus: [
{
// This means, when an option with value 'MENU_1' is hovered,
// the element '#my_menu_1' will be shown. This makes attaching
// menus to options REALLY SIMPLE
menu_element: $('#my_menu_1'),
target: ['MENU_1']
},
// However, lets say we have option value 'USER_ID_132', I need the
// target name to be dynamic. What better way to be dynamic than regex?
{
menu_element: $('#user_details_box'),
targets: ['USER_FORM', '/^USER_ID_[0-9]+$/'],
onOpen: function(target)
{
// here the TARGET can be interrogated, and the correct
// user info can be displayed
// Target will be 'USER_FORM' or 'USER_ID_3' or 'USER_ID_234'
// so if it is USER_FORM I can clear the form ready for input,
// and if the target starts with 'USER_ID_', I can parse out
// the user id, and display the correct user info!
}
}
]
});
如您所見,在小部件代碼中,我需要知道字符串是否為正則表達式的全部原因是,我可以決定將TARGET視為字符串(即“ USER_FORM”)還是將TARGET視為字符串。表達式(即'/ ^ USER_ID_ [0-9] + $ /'for USER_ID_234')
不幸的是,正則表達式字符串可以是“任何”。 您談論的正斜杠可能有很多字符。 即哈希(#)也將起作用。
其次,最多匹配5個字符而又不讓它們加倍,可以使用lookahead / lookbehind等方法來完成,但是會創建如此復雜的正則表達式,以便對其進行后處理更快。
在代碼中搜索正則表達式函數( preg_match
, preg_replace
等)可能更快,以便能夠推斷出使用正則表達式的位置。
$var = '#placeholder#';
在PHP中是有效的正則表達式,但不必是其中之一:
const ESCAPECHAR = '#';
$var = 'text';
$regexp = ESCAPECHAR . $var . ESCAPECHAR;
也有效,但可能不會這樣。
為了防止在修飾符部分重復,我會這樣做:
^/.+/(?:(?=[^i]*i[^i]*)?(?=[^m]*m[^m]*)?(?=[^s]*s[^s]*)?(?=[^x]*x[^x]*)?(?=[^e]*e[^e]*)?)?$
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.