crbon
crbon

Reputation: 175

Exclude only tailing space character from regex match

I am trying to select only the the street / unit number from an address string.

My regex pattern is /^[\d\s,\-\/]*/

Currently my regex matches digits '/' '-' and space characters before any alphabetic characters. However I would like to exlude the tailing space character.

My regex matches

61/2Sydney Road, Manly NSW (note the space character after the '2')

Instead of

61/2 Sydney Road, Manly NSW


Here are some sample addresses strings:

61/2 Sydney Road, Manly NSW

61-2 Sydney Road, Manly NSW

61/2 3 Sydney Road, Manly NSW

Upvotes: 1

Views: 120

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627101

Since your expected matches are not empty string (and your current expression - /^[\d\s,\-\/]*/ - matches empty strings if there is no [\d\s,\-\/]* pattern match at the start of the string) and there is always a digit at the end of the match, you may add \d at the end of your pattern:

/^[\d\s,\/-]*\d/
             ^^

See the regex demo.

Pattern details

  • ^ - start of string anchor
  • [\d\s,\/-]* - zero or more digits, whitespaces, ,, / or - (note there is no need to escape the hyphen when it is located at the very end of the character class)
  • \d - a digit.

Upvotes: 3

Related Questions