如何从字符串中删除特殊字符

时间:2015-09-14 15:02:34

标签: ruby regex

我有一行包含库名,我需要一个没有特殊字符的干净名称列表。

 include ':app', ':Android-RSS-Reader-Library-master', ':facebook',
 ':Forecast', ':headerListView', ':library-sliding-menu',
 /*':PanoramaGL',*/ ':stripe', ':ProgressWheel-master', ':UIL_library',
 ':volley'

这是我的功能,但它给了我带有特殊字符的名字。我怎么能删除它们?

def getLib

  File.open('./out.txt', 'w') do |f|
    File.foreach('./settings.gradle') do |line|
      # directory_name = line[/':([^']+)'/, 1]
      directory_name = line.split(/\'\:/)

      f.puts directory_name
    end 
  end 
end

结果是:

include  app',  Android-RSS-Reader-Library-master',  facebook',  Forecast',  headerListView',  library-sliding-menu', /* PanoramaGL',*/ stripe',  ProgressWheel-master',  UIL_library',  volley'

1 个答案:

答案 0 :(得分:0)

如果您想要通过逗号在文件中列出的项目数组,您可以这样做:

line.scan(/'(:.+?)'/).flatten
# => [":app", ":Android-RSS-Reader-Library-master", ":facebook", ":Forecast", ":headerListView", ":library-sliding-menu", ":PanoramaGL", ":stripe", ":ProgressWheel-master", ":UIL_library", ":volley"]

如果名称中不需要冒号,只需将其移出大括号:

line.scan(/':(.+?)'/).flatten
=> ["app", "Android-RSS-Reader-Library-master", "facebook", "Forecast", "headerListView", "library-sliding-menu", "PanoramaGL", "stripe", "ProgressWheel-master", "UIL_library", "volley"]