匹配字符串末尾的正则表达式不起作用



我想识别给定字符串中的门牌号。您可以在这里找到一些示例输入:

"My house number is 23"
"23"
"23a"
"23 a"
"The house number is 23 a and the street ist XY"
"The house number is 23 a"

我有以下regex:

d+(([s]{0,1}[a-zA-Z]{0,1}[s])*|[s]{0,1}[a-zA-Z]{0,1}$)

但是它不能捕获在行尾有数字后跟字母的输入(例如the house number is 23 a)。

如有任何帮助,不胜感激。

PS:我终于需要typescript中的regex了。

如果我正确理解了你的问题,这应该可以工作:

(d+(s?[a-zA-Z]?s?|s?[a-zA-Z]$))

注:[s]{0,1}s?相同

https://regex101.com/r/r6WHFy/1

regex中的问题是The house number is 23 a匹配([s]{0,1}[a-zA-Z]{0,1}[s])*部分,因此解析器"不需要";查找包含字符串结束符号的部分

您也可以使用字边界来编写模式,而不使用替代|

bd+(?:s*[a-zA-Z])?b
  • bA字边界
  • d+匹配1+数字
  • (?:s*[a-zA-Z])?可选地匹配可选的空白字符和a-zA-Z
  • bA字边界

const regex = /bd+(?:s*[a-zA-Z])?b/;
[
"My house number is 23",
"23",
"23a",
"23 a",
"The house number is 23 a and the street ist XY",
"The house number is 23 a"
].forEach(s => console.log(s.match(regex)[0]));

Regex演示

最新更新