The following program I wrote
var textRegEx = /.{1,3}/g;
var text = "AUZ01A1";
var woohooMatch = text.match(textRegEx);
var finalResult = woohooMatch.join(' - ')
console.log(finalResult);
gives the output as:
Output:
AUZ - 01A - 1
I want the output to be AUZ - 01 - A1
. How do I alter textRegEx to achieve this? I tried (2, 3} and some other things, but it doesn’t work. I am new to both javascript and regex. Can you please help?
3
Answers
You can use groups
()
to match pattern of 3,2,2 characters:Separate cases of
6
/7
,8
and other by a simpleswitch
statement:Or, if you prefer a tricky regex in a terse function:
Explanation for the regex, the rest is left as an exercise for the reader:
Try it on regex101.com.
Try it:
For your format, you can use an alternation with capture groups.
Then in the result, remove the full match and join the capture groups with
-
Note that a
.
matches any character. If you only want to match uppercase chars or digits, you can use a character class[A-Zd]
Explanation
^
Start of string(?:
Non capture group for the alternatives(.{2,3})(..)(..)
3 capture groups, where the first group has 2 or 3 chars|
Or(.)(.{7})
2 capture groups, where the first has a single char and the second group 7 chars)
Close the non capture groups$
End of stringRegex demo