使用正则表达式检索最后一次数字出现后的单词

时间:2017-06-21 12:13:08

标签: regex

我在字符串变量中收到streetname + doorno。我必须分开他们。我当前的正则表达式是/[0-9].*$/这适用于普通地址。但我有streetname也包含数值的地址。在这种情况下,streetname也被视为doorno

对于前,

[Correct] Street = Example Street 15B returns doorno = 15B

[Correct] Street = Example Street 15 B returns doorno = 15 B

[Correct] Street = Example Street returns doorno = null

[Correct] Street = Example Street15 returns doorno = 15

[Incorrect] Street = Example Street 158 7 returns doorno = 158 7. However I am expecting, the streetname = Example Street 158 & doorno = 7

[Incorrect] Street = Example Street 158 7 B returns doorno = 158 7 B. However I am expecting, the streetname = Example Street 158 & doorno = 7 B

[Incorrect] Street = Example Street 158 7B returns doorno = 158 7B. However I am expecting, the streetname = Example Street 158 & doorno = 7B

[Incorrect] Street = Example Street158 7 B returns doorno = 158 7B. However I am expecting, the streetname = Example Street158 & doorno = 7B

有人可以帮我修一下上述错误案例的正则表达式吗?

1 个答案:

答案 0 :(得分:0)

您可以使用

/^(.*\D)(\d.*)$/

匹配:

  • ^ - 字符串的开头
  • (.*\D) - 第1组:任何0+字符(除了换行符之外)直到最后一次出现的后续子模式(即\D\d.*$
  • (\d.*) - 第2组:一个数字,然后是任何0+字符(除了换行符之外)
  • $ - 字符串结束。