0

I have been trying to write regular expression for very simple string but have not been able to do so:

x = "abc 10 def price 100 ghi"

I tried regex:

"(\\w\\s)+(price)(\\s\\w)+"

String regex = "(\\w\\s)+(price)(\\s\\w)+";
String test = "abc 10 def price 100 ghi";
System.out.println(test.matches(regex));

It returns false.

This regex should match with the String above, however in my case regex is not matching the string.

Any help is highly appreciated.

The basic requirement is that any number of words/digits can come before "price" and any number of words/digits can come after "price". Although there should be space before and after price and there should be atleast one word before price and atleast one word after price. for example all of below string are acceptable:

abc 10de price xyz 
abc 10de price 1000 xyz
abc 10 de price 1000 xyz
abc 10 de de price 1000 xyz
6
  • 2
    What are you trying to match ? Commented May 7, 2014 at 13:18
  • @AmitJoki The regex is not matching the string above. Commented May 7, 2014 at 13:20
  • @Apolo The regex should match the string above. Commented May 7, 2014 at 13:20
  • 4
    HINT: \w matches a word character. Not a word. Commented May 7, 2014 at 13:21
  • 1
    should match String above is not enough info. .* matches string above too ;-) Commented May 7, 2014 at 13:21

2 Answers 2

2

This will match "at least one word then 'price' then at least one word":

(\\w+\\s+)+price(\\s+\\w+)+

Sign up to request clarification or add additional context in comments.

9 Comments

It's not character class. It's word followed by space(s), not alternatives. Also, incorrect, as it wouldn't match the example string given.
@AntonH I don't think so, [\\w\\s]+ can match "aaa", "aaa " and "aaa aaa".
@Apolo Yes it can, but that wasn't what was asked for. [\\w\\s]+price can also match aaaprice, but that isn't what is asked for.
@AntonH Yes, in fact it did match. But +1 for catching my misunderstanding of the question - I've updated it.
@bluskies It could match, but it would also match when there is a word like aaaprice. Your current solution is what OP was asking for.
|
2

This regex should match your string:

"(\\w+\\s)+(price)(\\s\\w+)+"

3 Comments

This doesn't match the case where there are repeated spaces.
In that case we can add + operator to the \\s
Thanks Prasanth, Your regex solves my problem, just accepted the answer that came first....

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.