I've created a regex to match particular positions of characters in a string. I've tested it, and it seems to be functioning OK. But I'm just curious if there's a better way to make this regex better. I appreciate it.
I need a word that have in position:
1: any letter 2: any number 3: any letter 4: have space 5: any number 6: any letter 7: any number
I have written a Regex like this:
/[a-zA-Z][0-9][a-zA-Z][\s][0-9][a-zA-Z][0-9]/;
CodePudding user response:
You can use this one:
/[a-z]\d[a-z]\s\d[a-z]\d/i
- the 'i' flag make the regexp case-insensitive
- \d is equivalent to [0-9]
- and you don't have to put '\s' between square brackets
CodePudding user response:
Your regex looks good, except that you likely want to:
- anchor the regex at the beginning and end (if you have no adjacent text around it),
- or use word boundary/expected adjacent chars (if your pattern is within a bigger string)
Also, \s
includes tab and newline, so you might want to use a simple space
instead.
Case 1:
/^[a-z][0-9][a-z] [0-9][a-z][0-9]$/i;
Case 2:
/\b[a-z][0-9][a-z] [0-9][a-z][0-9]\b/i;