我正在尝试替换 groovy 中的一个大字符串。但无法让它发挥作用。我使用的是 groovy 1.8.6
def textn = "http://10.33.0.69:8001/VS_SiteFacilityLookup/SiteFacilityLookupService?XSD=/com/enbridge/csim/ebo/module/common/serviceinterface/SiteFacilityLookupService.xsd"
textn = textn.replaceAll("http://10.33.0.69:8001/VS_SiteFacilityLookup/SiteFacilityLookupService?XSD=/com/enbridge/csim/ebo/module/common/serviceinterface/SiteFacilityLookupService.xsd", "hola")
println "textn : $textn"
这会打印出原始变量
如果我替换较短的字符串,它会正确替换它。
def textn = "http://10.33.0.69:8001/VS_SiteFacilityLookup/SiteFacilityLookupService?XSD=/com/enbridge/csim/ebo/module/common/serviceinterface/SiteFacilityLookupService.xsd"
textn = textn.replaceAll("SiteFacilityLookupService.xsd", "hola")
println "textn : $textn"
这会打印出预期的结果
最佳答案
尝试这个模式:
http:\/\/10.33.0.69:8001\/VS_SiteFacilityLookup\/SiteFacilityLookupService\?XSD=\/com\/enbridge\/csim\/ebo\/module\/common\/serviceinterface\/SiteFacilityLookupService.xsd
您需要记住转义特殊字符 - 例如?
-> \?
所以,总结一下,结果是:
def textn = "http://10.33.0.69:8001/VS_SiteFacilityLookup/SiteFacilityLookupService?XSD=/com/enbridge/csim/ebo/module/common/serviceinterface/SiteFacilityLookupService.xsd"
textn = textn.replaceAll("http:\/\/10.33.0.69:8001\/VS_SiteFacilityLookup\/SiteFacilityLookupService\?XSD=\/com\/enbridge\/csim\/ebo\/module\/common\/serviceinterface\/SiteFacilityLookupService.xsd", "hola")
println "textn : $textn"
我在这里测试过:http://gskinner.com/RegExr/
主题:在 groovy、Java 和(我希望!)任何其他语言中替换字符串时,字符串长度并不重要。重要的是,在较大的模式中,更容易省略一些导致不匹配的内容。因此,您应该使用简单且易于代码读者理解的模式。
例如:
http:\/\/.*
- 匹配以 http://
关于java - 替换groovy中的大字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11058437/