从文件路径中获取/提取.extension

时间:2018-05-28 06:10:01

标签: ruby string

我需要从以下路径中提取.扩展名:

  1. (_OasvkDSOEee_ruCXphIMsQ) /com.c.rb.gold.gbl.fw.proxy.component_jar/src/main/java/com/roup/ebus/mobile/api/common/resource/APIProxyResource.java
  2. (_7ZgAUO-qEeeFqO9kl3sUYw) /cbmo-thgcb-ext-gm.war/src/main/app/WEB-INF/classes/rules/THMBK/APIRequestResponseMapper.xml
  3. (_TM6vEFKjEee-NMziq4x8wA) /com.citi.rb.gold.memfis.sb.war/src/main/webapp/citibank/eclipselite/bank/memfis/sb/maintenance/SBBondCalculatorPopup.jsp
  4. 上面的每个文件路径都以" n"开头。白色空间的数量。我只需要.及其后面的部分,例如:

    • .java
    • .xml
    • .jsp
    • .anything

    请帮忙。

2 个答案:

答案 0 :(得分:1)

如果你有一个像这样的数组中的字符串:

strings = [
  "(_OasvkDSOEee_ruCXphIMsQ) /com.c.rb.gold.gbl.fw.proxy.component_jar/src/main/java/com/roup/ebus/mobile/api/common/resource/APIProxyResource.java",
  "(_7ZgAUO-qEeeFqO9kl3sUYw) /cbmo-thgcb-ext-gm.war/src/main/app/WEB-INF/classes/rules/THMBK/APIRequestResponseMapper.xml",
  "(_TM6vEFKjEee-NMziq4x8wA) /com.citi.rb.gold.memfis.sb.war/src/main/webapp/citibank/eclipselite/bank/memfis/sb/maintenance/SBBondCalculatorPopup.jsp"
]

你可以像这样获得扩展名:

strings.flat_map do |string|
  # in single line, regex is /(\.[^\.]+)$/
  # here is multiline form with explanation:
  regex = %r{
    (             # start of match group
      \.          # period
      [^\.]+ .    # any number of chars other than period
    )             # end of match group
    $             # end of string
  }x
  string.match(regex).captures
end
# => [".java", ".xml", ".jsp"]

答案 1 :(得分:1)

您可以使用File.extname

File.extname("/abcd/INF/classes/rules/THMBK/APIRequestResponseMapper.xml")
=> .xml
File.extname("fdsfdsdf /abcd/INF/classes/rules/THMBK/APIRequestResponseMapper.xml")
=> ".xml"