【问题标题】:Remove unwanted character in string using regex使用正则表达式删除字符串中不需要的字符
【发布时间】:2018-03-06 12:50:03
【问题描述】:

我正在尝试使用以下示例删除与特定模式不匹配的字符:

完全匹配 4 个字母 [a-zA-Z]{4} 后跟空格 \s{1,} 的模式,然后是 4 个以字母开头的字符,最后 3 个数字 [a-zA-Z]{1}[0-9]{3}

如果我提供ABEH A501; BIOL L340; BIOL Z620; Q799; ABEH A501,它将匹配除Q799 之外的所有内容,现在,我需要从字符串中删除/替换Q799

我尝试申请Negated Character Classes,但仍然没有得到想要的结果。

$mystring = "ABEH A501; BIOL L340; BIOL Z620; Q799; ABEH A501";
$string = preg_replace("/[^a-zA-Z]{4}\s{1,}[a-zA-Z]{1}[0-9]{3}/","",$mystring);

echo $string; //ABEH A501; BIOL L340; BIOL Z; ABEH A501

想要的结果应该是ABEH A501; BIOL L340; BIOL Z620; ABEH A501

Q799 已被删除,因此也是另一个匹配字符串的一部分,不确定这是由于错误的 regEx 还是错误的否定字符类应用。

【问题讨论】:

  • \s{1,0} 是什么意思?
  • 至少匹配一个或多个空格?
  • 由于可能会出现许多您想要的模式的错误变体,提取与preg_match()匹配的模式不是更好吗?
  • regex101.com/r/KXhIWa/3 根据这个你的正则表达式是无效的。使用 + 或 {1,}。 {1,0} 没有意义(“从 1 到 0 个字符”)
  • 至少一个或多个使用{1,}+{1,0}我认为这意味着从1到0

标签: php regex string pattern-matching


【解决方案1】:

在 PHP 中,您可以定义一个已知的良好匹配正则表达式并使用 PCRE 动词 (*SKIP)(*F) 来替换这些匹配:

$mystring = "ABEH A501; BIOL L340; BIOL Z620; Q799; ABEH A501";
echo preg_replace('/[a-zA-Z]{4}\s+[a-zA-Z]\d{3}(*SKIP)(*F)|\w+\W*/', '', $mystring);

RegEx Demo

输出:

ABEH A501; BIOL L340; BIOL Z620; ABEH A501

PHP Code Demo

【讨论】:

  • 您使用\s{1,8}而不是\s{1,0}的任何具体原因
  • 抱歉,它已修复。我将{1,0} 读作{1,8}。就像我现在的回答一样,它可以简单地是\s+
【解决方案2】:

这是解决问题的不同方法,但是嘿,它有效

<?php

$mystring = "ABEH A501; BIOL L340; BIOL Z620; Q799; ABEH A501";
preg_match_all("/[a-zA-Z]{4}\s{1,}[a-zA-Z]{1}[0-9]{3};?\s+?/",$mystring, $matches);
$result = "";
foreach($matches[0] as $match) {
    $result = $result.$match;
}
echo $result; //ABEH A501; BIOL L340; BIOL Z620; 

?>

【讨论】:

    猜你喜欢
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 2021-09-07
    相关资源
    最近更新 更多