1

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
  • System.out.println(product.replaceAll(".*x ([^;]*)(\(.*)", "$1")); There is double \\ Commented Sep 10, 2020 at 9:26

1 Answer 1

1

You can first match the digit(s) , then x 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 = "1 x Winter gloves \"Husky\" - wool(60 dollars)";
System.out.println(product.replaceAll("^\\d+ x ([^(]*)\\([^()]+\\)", "$1"));

Output

Winter gloves "Husky" - wool
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.