Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 计算内容表的正则表达式_Ruby On Rails_Ruby_Regex - Fatal编程技术网

Ruby on rails 计算内容表的正则表达式

Ruby on rails 计算内容表的正则表达式,ruby-on-rails,ruby,regex,Ruby On Rails,Ruby,Regex,我有这样的模板: <h1>asd</h1> ... <h1>asd</h1> ... <h2>asd</h2> ... <h2>asd</h2> ... asd ... 自闭症 ... 自闭症 ... 自闭症 ... 如何将其转换为 <h1>1. asd</h1> ... <h1>2. asd</h1> ...

我有这样的模板:

<h1>asd</h1>
...
<h1>asd</h1>
...
    <h2>asd</h2>
    ...
    <h2>asd</h2>
    ...
asd
...
自闭症
...
自闭症
...
自闭症
...
如何将其转换为

<h1>1. asd</h1>
...
<h1>2. asd</h1>
...
    <h2>2.1. asd</h2>
    ...
    <h2>2.2. asd</h2>
    ...
1。自闭症
...
2.自闭症
...
2.1. 自闭症
...
2.2. 自闭症
...

使用可安装在ruby 1.8.7上的oniguruma在ruby 1.8.7中使用正则表达式

string =<<X
<h1>asd</h1>
...
<h1>asd</h1>
...
    <h2>asd</h2>
    ...
    <h2>asd</h2>
    ...
X

puts string.gsub(/(?<=<h1>).*?(?=<h1>|\z)/m).with_index{|s, i|
  s = s.gsub(/(?<=<h2>).*?(?=<h2>|\z)/m).with_index{|s, j|
    "#{i+1}.#{j+1}. #{s}"
  }
  "#{i+1}. #{s}"
}

#=>
# <h1>1. asd</h1>
# ...
# <h1>2. asd</h1>
# ...
#     <h2>2.1. asd</h2>
#     ...
#     <h2>2.2. asd</h2>
#     ...

string=使用oniguruma,它可以安装在Ruby 1.8.7上

string =<<X
<h1>asd</h1>
...
<h1>asd</h1>
...
    <h2>asd</h2>
    ...
    <h2>asd</h2>
    ...
X

puts string.gsub(/(?<=<h1>).*?(?=<h1>|\z)/m).with_index{|s, i|
  s = s.gsub(/(?<=<h2>).*?(?=<h2>|\z)/m).with_index{|s, j|
    "#{i+1}.#{j+1}. #{s}"
  }
  "#{i+1}. #{s}"
}

#=>
# <h1>1. asd</h1>
# ...
# <h1>2. asd</h1>
# ...
#     <h2>2.1. asd</h2>
#     ...
#     <h2>2.2. asd</h2>
#     ...

string=我怀疑这是否可以用正则表达式实现。相反,我会使用客户端javascript在页面加载时执行此操作,通过使用普通javascript的
document.getElementsByTagName
或使用jQuery选择器搜索这些标题。@Vikdor我怀疑这不能用正则表达式完成。虽然,我同意你评论的后半部分。@sawa,但我不确定ruby扩展是否有助于使用正则表达式实现这一点。您下面的回答似乎使用了这样一个扩展/库。它是Ruby 1.9中的标准。它不是一个额外的库/扩展。它只是Ruby 1.8的一个后端口。我想我不用oniguruma也能做到。我怀疑用正则表达式能否做到这一点。相反,我会使用客户端javascript在页面加载时执行此操作,通过使用普通javascript的
document.getElementsByTagName
或使用jQuery选择器搜索这些标题。@Vikdor我怀疑这不能用正则表达式完成。虽然,我同意你评论的后半部分。@sawa,但我不确定ruby扩展是否有助于使用正则表达式实现这一点。您下面的回答似乎使用了这样一个扩展/库。它是Ruby 1.9中的标准。它不是一个额外的库/扩展。它只是Ruby 1.8的一个后端口。我想我不用oniguruma也能做到。但是如果我有标签之类的东西呢?我不想使用第三方宝石,如果它possible@sharpyfox我的代码足以满足您在问题中给出的要求。如果你有更深层的层次结构,也可以这样做。但是请注意,html标题标记以
结尾,因此您不必担心任意深度。你说的第三方宝石是什么意思?但是如果我有标签等等呢?我不想使用第三方宝石,如果它possible@sharpyfox我的代码足以满足您在问题中给出的要求。如果你有更深层的层次结构,也可以这样做。但是请注意,html标题标记以
结尾,因此您不必担心任意深度。第三方宝石是什么意思?