javascript - Regex: Check if (among others) specific characters are present in a string
问题描述
I'm working with next.js and I have a string (url). I need to check if the string contains at least 3x "/". Other chars are also present (letters, numbers and "-") - but they don't need to match something specific.
Example:
- "/apple/green-sour/south-spain" or "/red-orange/sweet/north-italy-toscany" -> check, if 3x "/" are present -> YES
- "/kiwi/new-zealan" -> check, if 3x "/" are present -> NO
I think I need the following snippets:
- [A-Za-Z0-9] -> numbers and chars
- [-] -> slash
- [/]{3} -> 3x "/"
I just don't know how to put them together in a regex. Could someone help me? Thanks a lot!
解决方案
You can repeat the /
followed by the accepted characters 3 or more times.
Note that [A-Za-Z0-9]
should be [A-Za-z0-9]
instead.
^(?:\/[A-Za-z0-9-]+){3,}
To not match -
only, or at the start or end, you can optionally repeat it:
^(?:\/[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*){3,}
推荐阅读
- javascript - Image4io 和 NodeJS:文档显然已经过时。如何上传图片?
- python - 在烧瓶 python 中解压 JSON 时出现关键错误
- c++ - 如何从源代码将 c++ 程序安装到 conda 环境中
- html - 文件输入 event.dataTransfer.files[0] 未定义
- javascript - 承诺使用 async/await 语法在 JavaScript 中进行 API 调用
- python - 使用python的请求包请求发布不起作用
- flutter - 在 Visual Studio 代码中,如何删除这一行?这很烦人
- python - 在数据框中查找所有非 latin1 (ISO 8859-1) 字符
- python-3.x - 在 MoviePy 视频中显示时间戳
- python - 在 Python Flask Jinja2 模板引擎中打印字符串时如何保留所有空格?