Reputation: 13
I want to create a regex for exactly 3 letter words only, separated by commas. 3 letter words can be padded with space(at most 1 on each side)
Valid Examples:
ORD
JFK, LAX
ABC,DEF, GHK,REW, ASD
Invalid Examples:
ORDA
OR
ORD,
JFK, LA
I tried the following but couldn't get it to work.
^(?:[A-Z ]+,)*[A-Z ]{3} +$
Upvotes: 1
Views: 655
Reputation: 1151
You can do this with the pattern: ^((:? ?[A-Z]{3} ?,)*(?: ?[A-Z]{3} ?))+$
var str = `ORD
JFK, LAX
ABC,DEF, GHK,REW, ASD
ORDA
OR
ORD,
JFK, LA`;
let result = str.match(/^((:? ?[A-Z]{3} ?,)*(?: ?[A-Z]{3} ?))+$/gm);
document.getElementById('match').innerHTML = result.join('<br>');
<p id="match"></p>
Upvotes: 0
Reputation: 28147
Try this: ^([ ]?[A-Z]{3}[ ]?,)*([ ]?[A-Z]{3}[ ]?)+$
https://regex101.com/r/HFeN0D/2/
It matches at least one three letter word (with spaces), preceded by any number of words three letter words with commas after them.
Upvotes: 1
Reputation: 521249
Try this pattern:
^[A-Z]{3}(?:[ ]?,[ ]?[A-Z]{3})*$
This pattern matches an initial three letter word, followed by two more terms separated by a comma with optional spaces.
Upvotes: 0