Scala转义换行符和制表符

时间:2016-01-27 21:10:13

标签: regex scala escaping

我正在尝试使用以下代码来删除网址中的制表符和换行符,但我仍然在输出中获得换行符和制表符。需要帮助解决这个问题。

http://www.bing.com/search?q=\tEnergy Source\tFuel (Coal)/Uranium Needed (tons)\tCO2 Emissions \r\n(tons)\tSulfur Dioxide and Other Emissions (tons)\tRadioactivity mSv (millisievert)\tSolid Waste (tons)\tAccidents\r\nQuarter 1\tCoal\t\t\t\t\t\t\r\n\tNuclear\t\t\t\t\t\t\r\nQuarter 2\tCoal\t\t\t\t\t\t\r\n\tNuclear\t\t\t\t\t\t\r\nQuarter 3\tCoal\t\t\t\t\t\t\r\n\tNuclear\t\t\t\t\t\t\r\nQuarter 4\tCoal\t\t\t\t\t\t\r\n\tNuclear\t\t\t\t\t\t\r\n

网址可以是

for i=1:n
if 
  statement
if 
  statement
if 
  statement
else 
  statement

for j=1:1000
if 
  statement
end
end

if 
  statement
else 
  statement
end

end
end
end
end

2 个答案:

答案 0 :(得分:2)

您的示例代码与我完美配合:

scala> val s = "http://www.bing.com/search?q=\tEnergy Source\tFuel (Coal)/Uranium Needed (tons)\tCO2 Emissions \r\n(tons)\tSulfur Dioxide and Other Emissions (tons)\tRadioactivity mSv (millisievert)\tSolid Waste (tons)\tAccidents\r\nQuarter 1\tCoal\t\t\t\t\t\t\r\n\tNuclear\t\t\t\t\t\t\r\nQuarter 2\tCoal\t\t\t\t\t\t\r\n\tNuclear\t\t\t\t\t\t\r\nQuarter 3\tCoal\t\t\t\t\t\t\r\n\tNuclear\t\t\t\t\t\t\r\nQuarter 4\tCoal\t\t\t\t\t\t\r\n\tNuclear\t\t\t\t\t\t\r\n"
scala> s.replaceAll("\\p{C}|\\s+|\\r$|\\\\t|\\\\n|\\\\r", "")
res0: String = http://www.bing.com/search?q=EnergySourceFuel(Coal)/UraniumNeeded(tons)CO2Emissions(tons)SulfurDioxideandOtherEmissions(tons)RadioactivitymSv(millisievert)SolidWaste(tons)AccidentsQuarter1CoalNuclearQuarter2CoalNuclearQuarter3CoalNuclearQuarter4CoalNuclear

答案 1 :(得分:0)

三重引号有助于清晰起见,因为未处理转义:

scala> s.replaceAll("""\t""", "")
res5: String =
"http://www.bing.com/search?q=Energy SourceFuel (Coal)/Uranium Needed (tons)CO2 Emissions

比较

scala> s.replaceAll("\\\\t", "")
res3: String =
"http://www.bing.com/search?q=  Energy Source   Fuel (Coal)/Uranium Needed (tons)       CO2 Emissions

我没有计算反斜杠。