macos - Grep not working with complex regular expression
问题描述
The goal is to use grep and find all URL paths containing an underscore. Underscores in the query string are ignored. Examples:
Positives:
/abc_bcd/def/
/foo_bar_foo
/image_bar?s=color
/foo_bar
/foo_remover?s=foo_bar
Negatives:
/foo
/foo/bar/foo
/foo/bar/foo?s=foo_bar
/foo-supersizer
/foosupersizer
/foobar
/foo-supersizer?s=foo_bar
foo_bar
foo bar bar_foo
foo_bar_foo
This regular expression works, but applying it inside of grep (on macOS) fails to yield any files even though there are ones containing matching paths.
Regular expression: /^(?=[^?\s]*_)(?:\/[-a-zA-Z0-9()@:%_?\+.~#&=]+)+\/?$/gm
RegEx test: https://regex101.com/r/tIYoP7/3
Grep command: grep -r "^(?=[^?\s]*_)(?:\/[-a-zA-Z0-9()@:%_?\+.~#&=]+)+\/?$" .
Does grep require special formatting for regular expressions on macOS?
解决方案
Given the sample input/output you posted all you need is:
$ grep '^/[^?]*_' file
/abc_bcd/def/
/foo_bar_foo
/image_bar?s=color
/foo_bar
/foo_remover?s=foo_bar
If that isn't all you need then edit your question to provide more truly representative sample input and expected output that includes cases where the above doesn't work.
推荐阅读
- python - 将 shell 命令设置为 Visual Studio Code 包含路径源
- swift - Initialisation of object with init function that provides default values for it's arguments
- azure-active-directory - 从使用同一 Azure AD 用户登录的不同应用程序注销
- c++ - 通过函数传递随机引擎 - 为什么不同的编译器表现不同
- sql - Tsql 查询从两列中找到最重复的字符串答案?
- flask - Kubernetes:自动确定另一个 pod/容器的 IP 地址
- php - PHP JSON 到变量
- swift - Swift 4 remove text from back button
- android - 错误:无效的父引用'style/Widget.AppCompat.Light.ActionBar.Solid.Inverse'
- javascript - 如何使用三元运算符在 Vue.js 中设置单选输入属性