新手问题 如何将匹配的文本块分别存储到数组

zfyp · 2012年06月15日 · 最后由 Anleb 回复于 2012年06月16日 · 2768 次阅读

想做一个 apache 的虚拟主机的配置管理脚本。我用正则表达式获取到了需要匹配的块,但是不知道要怎么把匹配的块存放。比如放到数组什么里面

表达式: /^[^#]\s*<VirtualHost.*?>[\s\S\n]+<\/VirtualHost>$/

#<VirtualHost *:80>
#    ServerAdmin [email protected]
#    DocumentRoot /www/docs/dummy-host.example.com
#    ServerName dummy-host.example.com
#    ErrorLog logs/dummy-host.example.com-error_log
#    CustomLog logs/dummy-host.example.com-access_log common
#</VirtualHost>
Listen *:80
NameVirtualHost *:80
  <VirtualHost   *:80>
          DirectoryIndex  index.php index.html index.htm
          ServerName  test.com
          DocumentRoot  /var/www/html/test.com
    ErrorLog logs/test.com-error_log
        CustomLog logs/test.com-access_log common
  </VirtualHost>

<VirtualHost   *:80>
          DirectoryIndex  index.html index.php index.htm
          ServerName  www.test1.com
          DocumentRoot  /var/www/html/test1.com
        ErrorLog logs/test1.com-error_log
        CustomLog logs/test1.com-access_log common
  </VirtualHost>

或者看这里 http://www.rubular.com/r/RWzr1WVmZH

表达式可以匹配到 www.test1.com、test.com 的区块 但是我要如何才能把匹配的块存到数组?类似下面一样

["  <VirtualHost   *:80>
          DirectoryIndex  index.php index.html index.htm
          ServerName  test.com
          DocumentRoot  /var/www/html/test.com
    ErrorLog logs/test.com-error_log
        CustomLog logs/test.com-access_log common
  </VirtualHost>";
"<VirtualHost   *:80>
          DirectoryIndex  index.html index.php index.htm
          ServerName  www.test1.com
          DocumentRoot  /var/www/html/test1.com
        ErrorLog logs/test1.com-error_log
        CustomLog logs/test1.com-access_log common
  </VirtualHost>"]

解决了。要把文本读出来存储为字段,然后再来做匹配 str=IO.read("c:/httpd.conf") ss=str.scan(/\n\s+DirectoryIndex[\s\w\d\.\/_-]+<\/VirtualHost>/m) ss.length.times{|tt| puts "这个是第#{tt+1}个匹配项:\n#{ss[tt]}"}

#2 楼 @zfyp

File.open('c:/httpd.conf') do |f| f.read.scan(/\n\s+DirectoryIndex[\s\w\d.\/_-]+<\/VirtualHost>/m).each_with_index do |m, i| puts "这个是第#{i}个匹配项:\n#{m}" end end

对于正则,字符串常见的处理有 sacn、split、或者通过=~匹配到全局变量$1,如: ‘’‘ "aaaaa".split(/正则/) 这是按正则分割 #=>Array Type

"aaaa'.scan(/正则/) 按正则匹配, #=>Array Type

"aaaa"=~/正则/ 可以利用全局$1存储第一次的匹配 #=>返回第一次出现的索引

或者如果对于 一个字符串数组,你还可以使用 Array.grep(/正则/) 来匹配 #=>Array Type

你也可以变态的 匹配--->结果----> ’oneArray<<‘ '''

需要 登录 后方可回复, 如果你还没有账号请 注册新账号