Regular expression - matches only 7 characters?

I am trying to match SEDOL (exactly 7 characters: 6 alphanumeric characters followed by 1 char number)

My regex

([A-Z0-9]{6})[0-9]{1}

right, but lines exceeding 7 characters that begin with a valid match also match (if you understand what I mean :)). For instance:

B3KMJP4

matches correctly, but also:

B3KMJP4x

which should not match.

Can someone show me how to avoid this?

+5
source share
4 answers

The dollar sign at the end of the regular expression (called the anchor) means the end of the line:

^([A-Z0-9]{6})\d$

"^" , xB3KMJP4 .

, , . , .

+6

start, end anchors :

^([A-Z 0-9]{6})[0-9]{1}$

6 - + char, . , .

{1}, [0-9] .

\d . , :

^([A-Z \d]{6})\d$
+5
 ^([A-Z\d]{6})\d$
  • Use ^ to start a line
  • $ for end of line
  • Remove excess space by simply noticing that
  • Changed 0-9 with \ d
  • Deleted {1} because it is redundant
+3
source

You forget that the regular expression matches anywhere in the string. To fix this, try this.

^([A-Z 0-9]{6})[0-9]{1}$

The ^ element means match at the beginning of a line, and $ means match at the end of a line.

+3
source

All Articles