Home > Back-end >  How to create a regex that will match anything that has 2 dimensions but will not match anything ove
How to create a regex that will match anything that has 2 dimensions but will not match anything ove

Time:10-18

I'm using a Java program and I'm trying to create a regular expression that will match anything that has two dimensions and will not match anything that goes over that.

I'm also trying to indicate two capture groups so that I can capture each dimension value separately. The dimensions have to be entered in the following format Some number x Other number (separated by the x)

Here are some examples to better explain what I'm trying to do:

  • S (26 in x 30 in): This should match and capture 26 and 30.
  • 20 x 40: This should match and capture 20 and 40.
  • Standard Size (10 x 40): This should match and capture 10 and 40.
  • 20 x 40 x 80: This should not match at all.
  • M (26 in x 30 in x 50 in): This should not match at all.

I have tried this regex but its still considering 3 dimensions as valid:

([\d.,] ).*?[xX] ?([\d,.] ).*

CodePudding user response:

I think this should get you what you want:

^[^\d]*(\d )[^\dx]*[xX][^\dx]*(\d )[^\d]*$

There may be an edge case that comes up where you have an x that is not the delimiter between the two numbers though. Not sure if this is a problem for your use case.

You can see it working here regex101

CodePudding user response:

Try this:

^(?!.* x .* x ).*?(\d )(?: [a-z] )? x (\d )

See live demo.

More than 2 dimensions are prevented from matching due to the negative lookahead anchored to start ^(?!.* x .* x )

CodePudding user response:

You could use the expression

^\D*(\d )[^x\d]*x[^x\d](\d )(?!\d)*(?![^x\d]*x[^x\d]*\d)

Demo

^          # match beginning of the string
\D*        # match 0 or more chars other than digits
(\d )      # match 1 or more digits and save to capture group 1
[^x\d]*    # match 0 or more chars other than 'x' and digits
x          # match x
[^x\d]*    # match 0 or more chars other than 'x' and digits
(\d )      # match 1 or more digits and save to capture group 2
(?!        # begin negative lookahead
  \d       # match a digit
)          # end negative lookahead
(?!        # begin negative lookahead
  [^x\d]*  # match 0 or more chars other than 'x' and digits
  x        # match 'x'
  [^x\d]*  # match 0 or more chars other than 'x' and digits
  \d       # match a digit
)          # end negative lookahead
  • Related