1

I'm trying to write javascript that validates a form value of a grid coordinate.

The grid has A to H and 1 to 8, with coordinates written as a letter followed by a number eg. "A1", "H8", "B6", "F3".

Can anyone give me a regex that will rule out anything other than coordinates within that range.

I tried the following:

/^[A-H][1-8]$/ 

based on my really limited knowledge of regex but that hasn't worked out

3
  • 2
    but that hasn't worked out - please edit the question to explain what you're expecting and what you're seeing (with related JS code/examples). That regex does what is described - matching strings that consist of only one letter, A to H, followed by a number, 1 to 8 - so if it "doesn't work" the problem isn't the regex itself. Commented Mar 25, 2021 at 9:18
  • Can you be a bit more specific about what you mean with "hasn't worked out", please? Your RegExp looks correct therefore it might be useful to know how it fails (no match at all, incorrect matches, etc.) and maybe see the code where it is used. Commented Mar 25, 2021 at 9:20
  • The regex say: looking for a line starting (^) with a capital letter in the range from "A" to "H" ([A-H]) followed by a digit in the range from "1" to "8" ([1-8]) and then the string must be end ($) Commented Mar 25, 2021 at 9:29

2 Answers 2

3

Your regexp looks correct, you may want to make it more robust in this way: /^\s*[A-H][1-8]\s*$/

This should match things like "A6" or "B7" even with spaces at the beginning or at the end.

A very useful tool to test your regexps is this: https://regex101.com/

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

3 Comments

This works great, I needed something like this too, thanks
@RodolfoSccani: I think the i-flag makes it all case insensitive! But there must be a capital letter!
@AndyU. you are right, I've corrected it. Thanks
1

To be sure your string starts with "A"- "H" followed by "1" - "8" it's correct to say ^[A-H][1-8] but then there may be some more content. So you can write a .* to allow some. To get this content, write it between ( and ) to build a group.

^[A-H][1-8](.*)$ 

If a line matches, you can get the content behind the range out of $1, the first group. Be sure, that your regex works case sensitive!

If you want to prevent matching lines with another range (like "B4 foo Bar bAz D7 xxx" you need a lookaround:

^[A-H][1-8]((?:(?![A-H][1-6]).)*)$ 

source: https://jex.im/regulex

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.