简体   繁体   English

如何匹配正则表达式,在匹配后删除所有内容

[英]How to match a regex, removing everything after the match

Say I have the following: preg_match("/ESP[0-9]?[0-9]/", $devid) 说我有以下内容: preg_match("/ESP[0-9]?[0-9]/", $devid)

I want to match data such as the following: 我想匹配以下数据:
$devid = "ESP1"
$devid = "ESP10"
$devid = "ESP78"

However, I don't want the string to contain anything that isn't matched in the regex. 但是,我不希望该字符串包含正则表达式中不匹配的任何内容。 For example: $devid = "ESP100" would return ESP10 例如: $devid = "ESP100"将返回ESP10
$devid = "ESP10234234" would return ESP10 $devid = "ESP10234234"将返回ESP10
$devid = "ESP78hello" would return ESP78 $devid = "ESP78hello"将返回ESP78

...and if there isn't a match, returning null (or equivalent). ...如果没有匹配项,则返回null(或等效值)。

In a way, I want to detect where preg_match finishes, and then remove the rest. 在某种程度上,我想检测preg_match在哪里完成,然后删除其余部分。

You can use preg_replace with a capture group: 您可以将preg_replace与捕获组一起使用:

$devid = preg_replace('/^(ESP\d{1,2}+).+/', '$1', $devid);

This regex matches & captures the text that we want to keep in group #1 and in replacement we put back $1 . 此正则表达式匹配并捕获我们要保留在组#1中的文本,在替换中,我们放回$1

or without the capture group use match reset \\K : 或没有捕获组,请使用match reset \\K

$devid = preg_replace('/^ESP\d{1,2}+\K.+/', '', $devid);

This regex matches text that we want to keep and then using \\K we reset match info. 此正则表达式匹配我们要保留的文本,然后使用\\K重置匹配信息。 In replacement we just use empty string. 在替换中,我们只使用空字符串。

RegEx Demo 正则演示

Note that {1,2}+ matches between 1 and 2 times, as many times as possible, without giving back . 请注意, {1,2}+匹配1至2次,且匹配次数尽可能多, 而不返回

You can use a third argument in preg_match like: 您可以在preg_match使用第三个参数,例如:

preg_match('/ESP\d\d?/', $string, $matches);
var_dump($matches[0] ?? NULL);

In case nothing is found NULL will be output. 如果未找到任何内容,则将输出NULL

Edit(cars10m): 编辑(cars10m):
From testing in rextester.com I found that $matches is returned as an array of length 0, when nothing is found, see here: http://rextester.com/UUM57869 通过rextester.com中的测试,我发现$ matches作为长度为0的数组返回,但未找到任何内容,请参见此处: http : //rextester.com/UUM57869

I believe you need the word boundary \\b . 我相信您需要边界\\b这个词。

preg_match("/\bESP\d{1,2}\b/", $devid, $match);

The word boundary makes sure it matches a word that starts with ESP and ends with one or two digits. 单词边界确保它与以ESP开头并以一位或两位数结尾的单词匹配。

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

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