如何使用正则表达式使用公共元素查找和替换文本?

时间:2017-08-10 12:21:08

标签: php regex

我在正则表达式上非常糟糕,需要以下方案的帮助。我需要找到并替换具有共同结构的文本,但一个方面将是不同的:

here is a string (with 3 values)
here is another string (with 5 values)

在上面的例子中,我需要找到并替换括号中的值。我不能单独用parens搜索,因为字符串可能包含其他parens。但是,需要被替换的parens值始终如一:(with # values) - 唯一的区别就是数字。

理想情况下,正则表达式会返回(with 3 values)(with 5 values),因此我可以使用简单的str_replace来更改文本。

这是PHP脚本中的正则表达式。

4 个答案:

答案 0 :(得分:0)

以下正则表达式适用于您:

/\(with (\d+) values\)/g

这匹配指定格式的字符串,并在捕获组中提供值,以便可以在替换中使用它。只有在一个字符串中有多个这样的标记时才需要最后的g标记。

演示here

但是,如果只能有一个数字,则以下内容将起作用:

/\(with (\d) values\)/g

或者,如果数字只能是大于1的数字,例如,则以下内容:

/\(with ([2-9]) values\)/g

答案 1 :(得分:0)

试试这个正则表达式:
\(with\s+\d+\s+values\)

演示here

答案 2 :(得分:0)

这样的事可能

$str ="here is another string (with 5 values)";

preg_match_all("/\(with (\d+) values\)/", $str, $out );

print_r( $out );

输出:

Array
(
    [0] => Array
        (
            [0] => (with 5 values)
        )

    [1] => Array
        (
            [0] => 5
        )

)

Here at ideone ...

它使用正则表达式

\(with (\d+) values\)

匹配文字左括号后跟字符串和#values ,捕获实际数字#,最后是结束括号。

它返回第一个维度中的完整匹配(带括号的字符串)和第二个维度中的实际数字

答案 3 :(得分:0)

如果我找对了你,你正在寻找括号内的三到五个项目(以逗号分隔) 这可以通过

完成
\(                        # "(" literally
    (?:[^,()]+,){2}       # not , or ( or ) exactly two times
    (?:(?:[^,()]+,){2})?  # repeated
    [^,()]+               # without the comma in the end
\)                        # the closing parenthesis

请参阅a demo on regex101.com

<小时/> 如果您真的只关注两个字符串变体,那么您可以非常轻松地执行

\(with (?:3|5) values\)

一般

\(with \d+ values\)

由@SchoolBoy提议。