2

I am passing a correct string formate but its not return true.

string dimensionsString= "13.5 inches high x 11.42 inches wide x 16.26 inches deep";
 // or 10.1 x 12.5 x 30.9 inches
 // or 10.1 x 12.5 x 30.9 inches ; 3.2 pounds

Regex rgxFormat = new Regex(@"^([0-9\.]+) ([a-z]+) x ([0-9\.]+) ([a-z]+) x ([0-9\.]+) ([a-z]+)( ; ([0-9\.]+) ([a-z]+))?$");
if (rgxFormat.IsMatch(dimensionsString))
{
     //match
}

I can't understand whats wrong with code ?

4
  • 3
    Your regex does not match several words after the number. See regex101.com/r/q8XJIB/2 where I just doubled each " ([a-z]+)". However, what are the pattern requirements? Is the number of words fixed? Commented Sep 13, 2018 at 12:12
  • 2
    @Wiktor Stribiżew there is 10.1 x 12.5 x 30.9 this pattern are fixed but, some time added string after number (2 word or more than 2 also possible).You suggestion is correct for 2 word string but if come more than ? like "13.5 inches high x 11.42 inches wide test x 16.26 inches deep"; Commented Sep 13, 2018 at 12:25
  • 1
    Replace them with (.*?). Try ^([0-9.]+) (.*?) x ([0-9\.]+) (.*?) x ([0-9.]+) (.*?)( ; ([0-9.]+) (.*))?$, see this demo. Commented Sep 13, 2018 at 12:26
  • 1
    @Wiktor Stribiżew Thanks . its working perfectly fine :-) Commented Sep 13, 2018 at 12:31

1 Answer 1

1

Your pattern only accounts for single words after the numbers. Allow any number of symbols there (with .* or .*?) to fix the pattern:

^([0-9.]+) (.*?) x ([0-9\.]+) (.*?) x ([0-9.]+) (.*?)( ; ([0-9.]+) (.*))?$

See the regex demo.

Note that the last .* is used with a greedy quantifier since it is the last unknown bit in the string (to match all the rest of the string). The .*? are non-greedy versions that match as few occurrences of any char but a newline as possible.

Replace regular spaces with \s to match any kind of whitespace if necessary.

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

1 Comment

sure, I will. its really help.

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.