英文:
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 ([^(]*)
If you want to use replace, you can match the opening till closing parenthesis after it and replace with group 1:
^\d+ x ([^(]*)\([^()]+\)
String product = "1 x Winter gloves \"Husky\" - wool(60 dollars)";
System.out.println(product.replaceAll("^\\d+ x ([^(]*)\\([^()]+\\)", "$1"));
Output
Winter gloves "Husky" - wool
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论