简体   繁体   English

正则表达式匹配一个数字后跟一个特定的字符串

[英]Regex to match a number followed by a specific string

I need to find a number followed by a specific string, within another string.我需要在另一个字符串中找到一个数字,后跟一个特定的字符串。

The initial string could be: some text 0.25mcg some more text some text 25mcg some more text初始字符串可以是: some text 0.25mcg some more text some text 25mcg some more text

so the number could be a decimal.所以这个数字可能是一个小数。 I need to be able to return the number (so 0.25 or 25) where ever the number is followed by 'mcg'我需要能够返回数字(所以 0.25 或 25),其中数字后跟“mcg”

Can anyone help me out.谁能帮我吗。 This doesn't work:这不起作用:

if(preg_match('(\d+mcg)', $item, $match))

Another option is to capture a digit with an optional decimal part \\d+(?:\\.\\d+)?另一种选择是使用可选的小数部分\\d+(?:\\.\\d+)? and use a word boundary \\b to prevent the match being part of a larger word.并使用单词边界\\b来防止匹配成为更大单词的一部分。

\b(\d+(?:\.\d+)?)mcg\b

Regex demo |正则表达式演示| Php demo php 演示

Code example代码示例

$re = '/\b(\d+(?:\.\d+)?)mcg\b/';
$str = 'some text 0.25mcg some more text some text 25mcg some more text';

preg_match_all($re, $str, $matches);
print_r($matches[1]);

Output输出

Array
(
    [0] => 0.25
    [1] => 25
)

If you want a match only instead of a capturing group you might also opt for a positive lookahead (?= instead.如果您只想要匹配而不是捕获组,您也可以选择积极的前瞻(?=代替。

\b\d+(?:\.\d+)?(?=mcg\b)

Regex demo |正则表达式演示| Php demo php 演示

It's a job for preg_match_all这是preg_match_all的工作

preg_match_all('/([\d.]+)mcg/', $item, $matches);

[\\d.]+ matches 1 or more digits or dot. [\\d.]+匹配 1 个或多个数字或点。

here is simple version:这是简单的版本:

<?php
$item1 = 'some text 0.25mcg some more text';
$item2 = 'some text 25mcg some more text';

if (preg_match('/([0-9\\.]+)\\s*mcg/', $item1, $match)) echo $match[1] . '<br>';
if (preg_match('/([0-9\\.]+)\\s*mcg/', $item2, $match)) echo $match[1] . '<br>';

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

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