红联Linux门户
Linux帮助

在linux中,能否在正则表达式中使用变量??

发布时间:2011-08-20 13:27:58来源:红联作者:wayne916
比如,查找开头为the的行,使用正则表达式 ^the
但是若查找的内容是不固定的,是个变量,可以在正则表达式中使用变量吗?
若能,语法怎样,是这样吗: ^$variable (查找开头为该变量的行),可是在正则表达式中$又有行尾的意思,到底该如何写带变量的正则表达式请教各位前辈。
文章评论

共有 6 条评论

  1. acrofox 于 2011-08-20 21:48:58发表:

    双引号中 $var 会被 shell 替换成 var 的值,所以正则表达式中已经没有 $ 了。

  2. chaipeng 于 2011-08-20 20:50:59发表:

    目前还不懂正则表达式

  3. gwssgc 于 2011-08-20 15:37:14发表:

    完全不能读懂):o:s 什么时候我才能成长啊!

  4. alick 于 2011-08-20 15:23:13发表:

    注意上面的代码不安全,根本没有对输入做检查。

  5. alick 于 2011-08-20 15:22:18发表:

    试了试,没问题。
    毕竟没有歧义。$指代行尾,必定位于模式串的结尾嘛。[code]$cat test.pl
    #!/usr/bin/perl

    my $string = "foobar";
    $re = <>;
    chomp $re;
    print(($string =~ /$re/) ? "match" : "not match");
    print "\n";
    $perl test.pl
    foo
    match
    $
    $cat test.sh
    #!/bin/bash

    string="foobar"
    read re
    echo "str=${string/$re/MATCH}"
    $bash test.sh
    foo
    str=MATCHbar
    $
    [/code]

  6. zjsxwc 于 2011-08-20 14:11:35发表:

    你试试不就知道了?