我想识别给定字符串中的门牌号。您可以在这里找到一些示例输入:
"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
b
A字边界d+
匹配1+数字(?:s*[a-zA-Z])?
可选地匹配可选的空白字符和a-zA-Zb
A字边界
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演示