Java正则表达式,从特定字符提取子字符串到另一个字符。

huangapple go评论70阅读模式
英文:

Java regex substring from certain charater to another character

问题

i'm new here and this is my first question. I researched this topic as best as I could and almost found my solution. I have examples of strings that look like this:

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

I am trying to extract only the product name: Winter gloves "Husky" - wool
I know there are two possible solutions, either with .replaceAll method or with Pattern Matcher.

I tried this:

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

output is this :

Winter gloves "Husky" - wool(60 dollars)

I just need to finalize the formula so that the string will "stop" at the first "(" symbol it encounters. This way I will get my desired result: Winter gloves "Husky" - wool

Any help is appreciated.
Thanky you.

英文:

i'm new here and this is my first question. I researched this topic as best as I could and almost found my solution. I have examples of strings that look like this:

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

I am trying to extract only the product name: Winter gloves "Husky" - wool
I know there are two possible solutions, either with .replaceAll method or with Pattern Matcher.

I tried this:

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

output is this :

Winter gloves "Husky" - wool(60 dollars)

I just need to finalize the formula so that the string will "stop" at the first "(" symbol it encounters. This way I will get my desired result: Winter gloves "Husky" - wool

Any help is appreciated.
Thanky you.

答案1

得分: 1

首先可以匹配数字,然后匹配 <code> x </code>,并在第1组中捕获匹配除了 `(` 而不是 `;` 的任何字符。

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

[正则演示](https://regex101.com/r/t8yEJm/1)

如果要使用替换,可以匹配其后的开括号到闭括号,并替换为第1组内容:

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

[正则演示](https://regex101.com/r/bfSVlz/1) | [Java 演示](https://ideone.com/DJOPQ0)

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

输出

    Winter gloves \"Husky\" - wool
英文:

You can first match the digit(s) , then <code> x </code> and capture in group 1 matching any char except ( instead of ;

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

Regex demo

If you want to use replace, you can match the opening till closing parenthesis after it and replace with group 1:

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

Regex demo | Java demo

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

Output

Winter gloves &quot;Husky&quot; - wool

huangapple
  • 本文由 发表于 2020年9月10日 17:18:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63826589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定