【问题标题】:Java regex substring from certain charater to another character从某个字符到另一个字符的 Java 正则表达式子字符串
【发布时间】:2020-12-28 18:26:52
【问题描述】:

我是新来的,这是我的第一个问题。我尽我所能研究了这个话题,几乎找到了我的解决方案。我有如下字符串示例:

String product = "1 x Winter gloves \"Husky\" - wool(60 dollars)"

我正在尝试仅提取产品名称:Winter gloves "Husky" - wool
我知道有两种可能的解决方案,使用 .replaceAll 方法或使用模式匹配器。

我试过了:

System.out.println(product.replaceAll(".*x ([^;]*)", "$1"));

输出是这样的:

Winter gloves "Husky" - wool(60 dollars)

我只需要最终确定公式,以便字符串在遇到的第一个“(”符号处“停止”。这样我会得到我想要的结果:冬季手套“哈士奇” - 羊毛

感谢任何帮助。 谢谢你。

【问题讨论】:

  • System.out.println(product.replaceAll(".*x ([^;]*)(\(.*)", "$1")); 有双\\跨度>

标签: java regex substring


【解决方案1】:

您可以先匹配 digit(s) ,然后匹配 x 并在第 1 组中捕获匹配除 ( 之外的任何字符,而不是 ;

^\d+ x ([^(]*)

Regex demo

如果你想使用替换,你可以匹配它后面的左括号并替换为第1组:

^\d+ x ([^(]*)\([^()]+\)

Regex demo | Java demo

String product = "1 x Winter gloves \"Husky\" - wool(60 dollars)";
System.out.println(product.replaceAll("^\\d+ x ([^(]*)\\([^()]+\\)", "$1"));

输出

Winter gloves "Husky" - wool

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-16
    • 2017-03-19
    • 1970-01-01
    • 2021-04-24
    • 2013-03-31
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    相关资源
    最近更新 更多