不匹配 spec.ts 和 spec.tsx 但应匹配任何其他 .ts 和 .tsx 的正则表达式
Regex that doesn't match spec.ts and spec.tsx but should match any other .ts and .tsx
我编写的这个正则表达式匹配任何 .ts 或 .tsx 文件名,但不应匹配 spec.tsx 或 spec.ts。下面是我写的正则表达式。
(?!spec)\.(ts|tsx)$
但它无法忽略.spec.tsx 和spec.ts 文件。我在这里做错了什么?请指教
否定先行语法 ((?!...)
) 从它在正则表达式中的任何地方看起来 先行。因此,您的 (?!spec)
正在与该点之后的内容进行比较,就在 \.
之前。换句话说,它与文件扩展名 .ts
或 .tsx
进行比较。否定先行不匹配,因此不会拒绝整个字符串作为匹配项。
你想要一个负面的lookbehind正则表达式:
(?<!spec)\.(ts|tsx)$
这里有一个demo(见屏幕左侧的"unit tests"link)。
以上假设您的正则表达式风格支持负向回顾;并非所有类型的正则表达式都可以。如果您碰巧使用的正则表达式风格不支持负向后视,则可以使用更复杂的负向前视:
^(?!.*spec\.tsx?$).*\.tsx?$
这实际上是说 "Starting from the beginning, make sure the string doesn't end in spec.ts
or spec.tsx
. If it doesn't end in that, then match if it ends in .ts
or .tsx
"
我编写的这个正则表达式匹配任何 .ts 或 .tsx 文件名,但不应匹配 spec.tsx 或 spec.ts。下面是我写的正则表达式。
(?!spec)\.(ts|tsx)$
但它无法忽略.spec.tsx 和spec.ts 文件。我在这里做错了什么?请指教
否定先行语法 ((?!...)
) 从它在正则表达式中的任何地方看起来 先行。因此,您的 (?!spec)
正在与该点之后的内容进行比较,就在 \.
之前。换句话说,它与文件扩展名 .ts
或 .tsx
进行比较。否定先行不匹配,因此不会拒绝整个字符串作为匹配项。
你想要一个负面的lookbehind正则表达式:
(?<!spec)\.(ts|tsx)$
这里有一个demo(见屏幕左侧的"unit tests"link)。
以上假设您的正则表达式风格支持负向回顾;并非所有类型的正则表达式都可以。如果您碰巧使用的正则表达式风格不支持负向后视,则可以使用更复杂的负向前视:
^(?!.*spec\.tsx?$).*\.tsx?$
这实际上是说 "Starting from the beginning, make sure the string doesn't end in spec.ts
or spec.tsx
. If it doesn't end in that, then match if it ends in .ts
or .tsx
"