+ -
当前位置:首页 → 问答吧 → 在linux中,能否在正则表达式中使用变量??

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

时间:2011-08-20

来源:互联网

比如,查找开头为the的行,使用正则表达式  ^the   
但是若查找的内容是不固定的,是个变量,可以在正则表达式中使用变量吗?
若能,语法怎样,是这样吗:  ^$variable  (查找开头为该变量的行),可是在正则表达式中$又有行尾的意思,到底该如何写带变量的正则表达式请教各位前辈。

作者: wayne916   发布时间: 2011-08-20

你试试不就知道了?

作者: zjsxwc   发布时间: 2011-08-20

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

  3. my $string = "foobar";
  4. $re = <>;
  5. chomp $re;
  6. print(($string =~ /$re/) ? "match" : "not match");
  7. print "\n";
  8. $perl test.pl
  9. foo
  10. match
  11. $
  12. $cat test.sh
  13. #!/bin/bash

  14. string="foobar"
  15. read re
  16. echo "str=${string/$re/MATCH}"
  17. $bash test.sh
  18. foo
  19. str=MATCHbar
  20. $
复制代码

作者: alick   发布时间: 2011-08-20

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

作者: alick   发布时间: 2011-08-20

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

作者: gwssgc   发布时间: 2011-08-20