【问题标题】:regular expression keep one or zero with regexpall [duplicate]正则表达式使用 regexpall 保持 1 或 0 [重复]
【发布时间】:2020-09-01 09:02:22
【问题描述】:

我想使用 replaceall 和正则表达式将一些文本转换为其他内容。

我的文字如下:

This is with something extra constraint xhiho,

This is without something extra constraint hfdlh

现在我想要的结果如下:

This is with something extra, --constraint xhiho

This is without something extra -- constraint hfdlh

所以我需要把 2 - 放在单词约束之前,如果最后有 , 把它放在 2 - 前面

我尝试了以下代码:

oConvert = oConvert.replaceAll("constraint(.*)(,?)", "$2--constraint$1");

但它不起作用,它没有在2个-前面给出,

【问题讨论】:

  • 使用constraint([^,]*)(,?)constraint(.*[^,])(,?)
  • 两者都不起作用
  • 试试oConvert = oConvert.replaceAll("(?m)(\\s*)constraint([^,]*)(,?)$", "$3$1--constraint$2");
  • 对 no , is 的行也这样做
  • 但是您确实要求这样做。 This is without something extra constraint hfdlh 必须变为 This is without something extra -- constraint hfdlh

标签: java regex replaceall


【解决方案1】:

你可以使用:

str = str.replaceAll("(\\h+constraint\\h+[^,]*)(,?)", "$2 --$1");

RegEx Demo

正则表达式详细信息:

  • (: 开始捕获组 #1
    • \h+: 匹配 1+ 个空格
    • constraint:匹配constraint
    • \h+: 匹配 1+ 个空格
    • [^,]*:匹配 0 个或多个不是 , 的任何字符
  • ): 捕获组 #1 结束
  • (: 捕获组 #2 的开始
    • ,?:匹配一个可选的逗号
  • ): 捕获组 #2 结束

【讨论】:

  • 这不行,它没有把 , 放在 --
  • -- 之前会有一个,。您是否检查了链接演示中的输出:regex101.com/r/jjHC5N/1
  • 请注意,如果尾随逗号不在 then 结尾,则 $ 将不匹配,您应该使用:(\\h+constraint\\h+[^,]*)(,?) 作为正则表达式。
  • 逗号后面是空格,所以第二个选项更好,但它也会在不应该出现的 -- 前面放一个 ,
  • 但是你想把,放在--之前,如果最后有逗号的话。您能否检查regex101.com/r/jjHC5N/2 中的输出,如果这是您想要的,请告诉我。
猜你喜欢
  • 1970-01-01
  • 2015-11-14
  • 2016-01-03
  • 1970-01-01
  • 2012-12-16
  • 2021-01-23
  • 1970-01-01
  • 2018-06-01
  • 1970-01-01
相关资源
最近更新 更多