1

我正在尝试替换 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"

这打印出预期的结果

4

1 回答 1

2

试试这个模式:

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://

于 2012-06-15T21:34:54.640 回答