1

Let's say I want to restrict a user to enter a suburb or a postcode but not both,

I want 'suburb' to pass as it's all alpha characters, I want '1234' to pass as it's all numeric, but I can't figure out how to map and either or inside a regex.

Here's what I've tried.

var string = 'word'; var resultA = !(string.match(/^[a-z|0-9]+$/i)); alert(resultA); 

So I need:

'word' => true '1234' => true 'word word' => true, 'word 123' => false, 'word2' => false 

When it runs through the expression.

2
  • That's a good point @stribizhev, how can I accommodate for that? Commented Dec 15, 2015 at 22:15
  • @ShannonHochkins, it seems like you're forgetting that post codes sometimes have hyphens, and that suburbs sometimes have periods. You may want to reconsider formalizing something that really isn't meant to be matched by a regular expression. Commented Dec 15, 2015 at 22:24

2 Answers 2

3

You can use this regex to match either alphabets or digits in input:

var resultA = /^([A-Za-z]+|[0-9]+)$/.test(string); 
Sign up to request clarification or add additional context in comments.

4 Comments

Thankyou!, and if I wanted to allow whitespace in between words? so if I had 'some place', I would like that to succeed too!
then you can use: /^([A-Za-z]+(?: [A-Za-z]+)*|[0-9]+)$/
you'd be better off just adding the space to the allowed characters as [a-zA-Z ]
That won't be correct because [a-zA-Z ] will also match an input with just spaces.
0

When developers ask how to overcomplicate their regular expressions, I usually recommend that they take a step back and just write some code, and throw in regex for the parts they can formalize well.

You asked how to determine if a string is entirely alpha characters or entirely numbers.

A regex to detect all alphabetic characters is

/^[a-z]*$/i 

A regex to detect all numeric characters is

/^\d*$/ 

Combining them is simply:

function valid(str) { return /^[a-z]*$/i.test(str) || /^\d*$/.test(str); } 

Now if you want to combine it all into a single regular expression you just have to use the | regular expression operation:

function valid(str) { return /^[a-z]*$|^\d*$/i.test(str); } 

This can of course be simplified if you use a grouping operator:

/^([a-z]*|\d*)$/i 

don't simplify it. It's easier to read and easier to reason about regular expressions when they're shorter and match simpler patterns. Use more small regular expressions, rather than fewer longer regular expressions, even if the code could be made shorter. Future you will thank past you for making the code easier to understand.

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.