捕获1位数,但其他标准也+正则表达式

时间:2015-08-12 23:58:04

标签: regex

如何从0行抓取K'0 我正在捕获其他所有东西。

这是我的REGEX EXAMPLE

这是我的正则表达 K'(?P<name1>81|61|64|44|86|678|41|49|33|685|1(?:33|45)?|\d{1,3})?\d+

K'0     <<<----adding the ? here |\d{1,3})?\d+ as want to pick up if there is only 
K'93        <<<--- 1 number 2 number or 3 numbers (ie. K'0, K'93, K'935 )
K'935
K'8134567
K'81345678
K'6134516789
K'61345678
K'643456
K'646345678
K'1234567890
K'12345678901
K'1454567890    <<<--- want 145 returned and not 1 
K'13345678901   <<<--- want 133 returned and not 1 
K'3214567890123
K'32134567890123
K'3654567890123
K'8934567890123
K'6554567890123


I am interested in the digits after K'
I am looking to do this using regex but not sure if it can be done. What I want is:
if the number starts with 81 return 81 
if the number starts with 61 return 61 
...
if the number starts with something i am not interested in return other(or its first digits of 1-3)

The above criteria works:

but what I also want is:
if the fist digit is 1 then return 1 BUT 
if the fist digit is 1 and the 2nd and 3rd digit are 45 return 145 and don't return just 1  
if the fist digit is 1 and the 2nd and 3rd digit are 33 return 133 and don't return just 1

I presume I have to put something inside this part of the regex |(1)\d+|

Questions:
Does regex sort the data first?
Is the order of the regex search important to how it is implemented? i deally I do not want this. 

3 个答案:

答案 0 :(得分:1)

您可以将正则表达式更改为:

K'(?P<name1>0|81|61|64|44|86|678|41|49|33|685|1(?:33|45)?|\d{1,3})?\d*
notice -----^                                             and also --^

<强> Working demo

enter image description here

答案 1 :(得分:0)

这有点棘手。问题是正则表达式的两个部分(括号中的部分和\d+)可以匹配相同的文本。使第一部分成为可选(命名捕获),让第二部分\d+具有更高的优先级,并且&#34;吃掉&#34;你的第一个数字,因为它必须匹配至少1位数(由于+量词),并且第一个组是可选的不必捕获任何数字。

您可以通过\d+

上设置的环视来实现您想要的行为
K'(?P<name1>0|678|685|1(?:33|45)?|81|61|64|44|86|41|49|33|\d{1,3})?(?:(?<!0)\d+|(?<=0)\d*)

请参阅demo

(?:(?<!0)\d+|(?<=0)\d*)部分意味着如果我们之前没有0,我们可以捕获1位或更多位数(至少1位)。如果有零,我们应该捕获0或更多位数(可以是0)。

答案 2 :(得分:0)

我在您的指定群组中接受001之类的数字,您只需将上次\d+更改为\d*,无需另外添加0替代(DEMO)。我是另一种情况,将0作为替代。

但是,您也可以将正则表达式修改为:

K'(?P<name1>0|8[16]|6[14]|4[149]|33|6(?:78|85)|1(?:33|45)?|\d{0,3})\d*

它不会改变它匹配的东西,但应该通过提取一个共同的模式来提高它的速度。就像当您使用685以简单替代方式搜索(678|685)时,它会先与6匹配,然后与7不匹配,因此它会再次回溯到开头,并从6,并匹配85。使用(6(?:78|85))时,它只匹配6一次,然后与7不匹配,并直接尝试匹配8

另外,如果您真的想要匹配没有数字的字符串(仅K'),您可以将\d{1,3})?\d*更改为\d{0,3})\d*,因为它实际上是相同的。替代的最后一个选项是\d({1,3},从一到三位数,但整个替代方案是?元字符(零或一次),所以即使替代方法不匹配任何数字,正则表达式将匹配,如果正则表达式匹配的前一个和更多片段。所以它意味着相同,从0到3位(\d{0,3})。有了这个,正则表达式将首先尝试通过替代匹配数字,如果仍然存在一些差异,它将与\d*匹配。

DEMO