【问题标题】:Regular expression in template literals. Escaping characters模板文字中的正则表达式。转义字符
【发布时间】:2021-02-23 14:34:38
【问题描述】:

我正在尝试将 graphql-constraint-directive 与 apollo graphql 服务器一起使用。 我需要把注册。像这样的模板文字中的表达式

const typeDefs =   gql`
input ClaimInput {
  id: String!
  date: String!
  phone: String @constraint(pattern: "^05\d([-]{0,1})\d{7}$")
  email: String
  invoice: String
  doctorId: String
  therapy: [TherapyInput]
  files: [FileInput]
}
`

它对我不起作用。没有匹配。正则表达式是正确的。该示例适用于这个 @constraint(pattern: "^[0-9a-zA-Z]$")*.

所以我意识到我的模板字面量 typeDefs 中的 ^05\d([-]{0,1})\d{7}$ 有问题。

我已签入 Node REPL:

> v = `^05\d([-]{0,1})\d{7}$`
'^05d([-]{0,1})d{7}$'
> v = `^05\\d([-]{0,1})\d{7}$`
'^05\\d([-]{0,1})d{7}$'

当我把 \d \ 忽略。 当我把 \\d 我有 \\d.不是我需要的。

如何处理这种情况?

编辑: 我认为问题出在 'apollo-server' 的 gql

当我改为:

const typeDefs = gql`

input ClaimInput {
  id: String!
  date: String!
  phone: String @constraint(pattern: "^05\\d([-]{0,1})\\d{7}$")
  email: String
  invoice: String
  doctorId: String
  therapy: [TherapyInput]
  files: [FileInput]
}
`

我有一个错误: GraphQLError:语法错误:无效的字符转义序列:\d。

当我变成

const typeDefsRaw = String.raw`
input ClaimInput {
  id: String!
  date: String!
  phone: String @constraint(pattern: "^05\d([-]{0,1})\d{7}$")
  email: String
  invoice: String
  doctorId: String
  therapy: [TherapyInput]
  files: [FileInput]
}
`
const typeDefs = gql`${typeDefsRaw}`;

我遇到了同样的错误: GraphQLError:语法错误:无效的字符转义序列:\d。

【问题讨论】:

标签: javascript graphql apollo-server string-literals template-literals


【解决方案1】:

你可以使用String.raw:

v = String.raw`^05\d([-]{0,1})\d{7}$`

\\d 如果您不/不能使用String.raw 也是正确的。它只显示为\\d,因为 REPL 中的预览必须是可复制粘贴的字符串。如果你console.log(v),你只会看到一个反斜杠。

【讨论】:

  • 感谢您的快速答复。我现在去检查一下。
  • 你答对了。谢谢你。但是它并没有解决我的问题。
【解决方案2】:

\d 表示数字,因此解决方法是使用[0-9] 而不是\d

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 2010-09-21
    相关资源
    最近更新 更多