2013-04-03 67 views
-8

怎么可能使用正则表达式来自定义正则表达式

BCT34385Z0000N07518Z 
BCT34395Z0000N07518Z 

分成BCT343格式?我使用这个magento来打破2种序列号,即BCT34385Z0000N07518ZBCT34395Z0000N07518Z为正则表达式,只是识别前6个字符,即BCT343

+6

什么是BCT343格式?你期望输出什么?你有什么尝试? – kamituel

+0

你只想抓住前6个字符吗? – Atropo

+0

如果有,请给我们一个格式规范的链接。如果不是的话,你至少应该解释一下这件事的结构。我们应该怎么知道你的标准是什么,否则呢? – jwueller

回答

1

这是一个非常不好的做法,而是因为你问它:

$str = 'BCT34385Z0000N07518Z'; 
preg_match('/^(.{6})(.*?)$/', $str, $result); 

echo $result[1]; // 'BCT343' 
echo $result[2]; // '85Z0000N07518Z' 

,或者如果你想要一个if语句:

$str = ...; 

if (preg_match('/^BCT343/', $str)) { 
    // yes! 
} 
+0

是否有可能使用正则表达式得到2个结果? – d3bug3r

+0

@danny我使用1个正则表达式并获得2个结果? –

+0

好的,谢谢哥们 – d3bug3r

1

如果你需要的是将这些字符串分为两部分(前六个字符和其余部分),那么根本不需要regex。你可以只用substr做到这一点:

<?php 
    $str1 = substr("BCT34385Z0000N07518Z", 0, 6); // BCT343 
    $str2 = substr("BCT34385Z0000N07518Z", 6); // 85Z0000N07518Z 
?> 

如果你想用正则表达式来做到这一点,你应该建立两个捕获组,一组为前六个字符,和另一个用于字符串的其余部分。正则表达式将如下所示:

/^(.{6})(.*)$/ 

/^    // Start of input 
(    // Start capture group 1 
    .    // Any charactger 
    {6}    // Repeated exactly 6 times 
)     // End of capture group 1 
(    // Start capture group 1 
    .    // Any character 
    *    // Repeated 0 or more times 
)     // End of capture group 2 
$/    // End of input 

,你应该使用preg_match()利用它。请记住,每个捕获组都将位于匹配数组的位置。看到这个RegExr的正则表达式的例子。

+0

需要正则表达式格式。我不能在magento上使用它,因为它期望在正则表达式 – d3bug3r