java - 替换groovy中的大字符串

标签 java string groovy replace

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

相关文章:

Java-如何正确停止 ScheduledExecutorService

c# - 使用 Linq 在 String 上运行正则表达式

java - 我可以用 Java 中字符串数组中的变量命名节点吗?

python - 迭代地将字符 [a-c] 分配给 Pandas Dataframe 中的行,直到列长度结束

java - 我是否需要在其自己的文件中将枚举定义为 'public',以便它可以在自己的包外被识别?

java - 如何在 java 中使用 php web 服务

java - 错误 :Execution failed for task ':app:packageRelease' . > 无法计算/../AndroidStudioProjects/../classes.jar 的哈希

groovy - 需要 Groovy 语法帮助从字符串生成闭包

spring - 当检查调用时,模拟方法也返回 null

groovy - 如何从 CliBuilder 获取非选项参数?