FirmView
FirmView

Reputation: 3150

Regex matching a space a digit and 8 characters

I want to match a string containing,

a space

any number of digit

a space

1-8 characters - (alphanumeric and special characters)

example,

 01 Stack   

This is what i tried,

\\s\\d+\\s[^.]{1, 8} - i tried here except for ., 

Upvotes: 2

Views: 843

Answers (2)

Richard Sitze
Richard Sitze

Reputation: 8463

Try this, to catch (and restrict to) the punctuation and alphanumerics: \s\d+\s[\p{Punct}\p{Alnum}]{1,8}; wrap it all in ^...$ if you want the begin/end line anchors.

If "any number of digits" means 1 or more digit, then the pattern above is fine. If it means "zero or more digits", then the \d+ needs to become \d*.

As an aside, the pattern [^.] will match anything that's not a period. It includes a bit too much, I think, and excludes a bit too much. So I'm opting for the more specific pattern [\p{Punct}\p{Alnum}].

See documentation here.

Upvotes: 2

Haozhun
Haozhun

Reputation: 6511

Try \\s\\d+\\s[^.]{1,8}? It looks like the only problem here is a superfluous space.

Also, \\S is for everything except whitespaces. [^ ] is for everything excpet space. . is for everything.

Upvotes: 2

Related Questions