如何编写正则表达式以匹配我的字符串

how to write a regex to match my string

本文关键字:我的 字符串 何编写 正则表达式      更新时间:2023-09-26

如何编写 JavaScript RegExp来匹配

'/api/users'
'/api/users/'
'/api/users?age=22'
'/api/users/?age=22'

但不是

'/api/users/id'

Regex到目前为止我已经尝试过:

new RegExp('^' + '/api/users' + ''/?''S*' + '$') 

如果我理解正确,您只想在查询字符串以 age 参数开头时才匹配它:

/'api'/users'/?('?age='d+|$)/

'api'/users'/?将匹配/api/users 或 api/users/

('?age='d+|$)将匹配 ?age=22 或字符串末尾 ($)

[编辑] 根据您的评论,更简单的表达式:

/'api'/users'/?('?|$)/

('?|$)将匹配查询字符串的开头 (?) 或字符串的结尾 ($)

为了完全匹配这些字符串并用作条件,您可以使用 .test(subjectString):

(/^'/api'/users'/?('?age='d+)?$/).test(subjectString)

这样的模式应该有效:

^/api/users/?('?age=22)?$

或者假设您要为 age 参数匹配的不仅仅是文字22

^/api/users/?('?age='d+)?$

这将匹配文字/api/users,后跟一个可选的',后跟一个可选的?age=和一个或多个数字。

当然,当您将其构建为正则表达式文本时,您需要转义正斜杠:

^/'/api'/users'/?('?age='d+)?/$

或者转义反斜杠并使用 RegExp 构造函数:

new RegExp("^/api/users/?(''?age=''d+)?$")

/api/users之后对/id使用负面展望:

/^'/api'/users(?!'/id).*$/

使用您的示例观看此内容的现场演示。