简体   繁体   English

编写正则表达式以获取两个分隔符之间的数字

[英]Write a regex to get numbers between two delimiters

I need to parse a string and get the numbers between 2 delimiters.我需要解析一个字符串并获取 2 个分隔符之间的数字。 I need to be sure they're numbers.我需要确定它们是数字。 I tried something like this but doesn't work as expected.我试过这样的事情,但没有按预期工作。

if (preg_match_all("/[^0-9](?<=First)(.*?)(?=Second)/s", $haystack, $result))
for ($i = 1; count($result) > $i; $i++) {
    print_r($result[$i]);
}

What's wrong with the regex?正则表达式有什么问题?

Huh, that's almost the one I supplied to your other question xD嗯,这几乎是我提供给你的另一个问题的那个 xD

Change the (.*?) to ([0-9]+)(.*?)更改为([0-9]+)

if (preg_match_all("/(?<=First)([0-9]+)(?=Second)/s", $haystack, $result))
for ($i = 1; count($result) > $i; $i++) {
    print_r($result[$i]);
}

.*? will match any character (except newlines) and to match only numbers in between your delimiters "First" and "Second", you will need to change it to [0-9] .将匹配任何字符(换行符除外)并且仅匹配分隔符“First”和“Second”之间的数字,您需要将其更改为[0-9] Then, I assume that there can't be nothing in between them, so we use a + instead of a * .然后,我假设它们之间不能有任何东西,所以我们使用+而不是*

I'm not sure why you used [^0-9] in the beginning.我不确定你为什么在开始时使用[^0-9] Usually [^0-9] means one character which is not a number, and putting it there doesn't really do something useful, at least in my opinion.通常[^0-9]表示一个不是数字的字符,把它放在那里并没有真正做一些有用的事情,至少在我看来。


Cleaning up a little, you could remove a few things that aren't needed to get the required output:稍微清理一下,您可以删除一些不需要的东西来获得所需的输出:

if (preg_match_all("/(?<=First)[0-9]+(?=Second)/", $haystack, $result))
   print_r($result[0]);

You can use [0-9] or \\d to ensure that the characters between the delimiters are numbers.您可以使用[0-9]\\d来确保分隔符之间的字符是数字。 using this you also won't need the lazy quantifier (unless your delimiters are actually numbers, too):使用这个你也不需要惰性量词(除非你的分隔符实际上也是数字):

preg_match_all("/[^0-9](?<=First)(\d*)(?=Second)/s", $haystack, $result)

Or或者

preg_match_all("/[^0-9](?<=First)([0-9]*)(?=Second)/s", $haystack, $result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM