在Cypress中转义特殊的正则表达式字符。

huangapple go评论62阅读模式
英文:

escaping special regex character in cypress

问题

我有一个在regex101.com上工作的正则表达式,用于我的用例,即只匹配括号内的六位数字字符串。我的尝试在表格行包含选择器中使用该正则表达式没有成功。它们要么没有转义括号并返回不应匹配的行,要么在应该找到匹配项时找不到匹配项。在regex101.com上,工作的表达式是 /\([0-9]{6}\)/gm。我已经尝试过双反斜杠,因为JS反斜杠本身就是一个特殊字符。这会导致过多匹配,并包括只有六位数字字符串(没有括号)的行。如果有更好的建议,欢迎提供。

cy.contains(
  'div[id="driverTableContainer"] table tbody tr',
  new RegExp("\\([0-9]{6}\\)", 'g')
)
  .nextAll()
  .then(($el) => {
    cy.task('log', $el.text())
  })
英文:

I have working regex at regex101.com for my use case which is to only match on a six digit numeric string that is enclosed in parenthesis. My attempts to use that regex in a table row contains selector are having no luck. They are either not escaping the parentheses & returning rows that should not match. Or they find no match when they should find matches. On regex101.com, the working expression is /\([0-9]{6}\)/gm. I've tried double backslashes since JS backslash is itself a special character. That is over-matching & including rows that merely have a six digit numeric string (no parentheses). Any better suggestions appreciated.

cy.contains(
  'div[id="driverTableContainer"] table tbody tr',
  new RegExp("\\([0-9]{6}\\)", 'g')
)
  .nextAll()
  .then(($el) => {
    cy.task('log', $el.text())
  })

答案1

得分: 3

You don't need to escape the backslash, this works (presuming your element selector works)

cy.contains(
  'div[id="driverTableContainer"] table tbody tr',
  new RegExp('[0-9]{6}')
)

You don't need the g since cy.contains() passes for 1 or more occurrences of the string.

Also, cy.contains() only returns the first row found. If you want multiple rows, you need to cy.get() then filter

const re = new RegExp('[0-9]{6}')
cy.get('div[id="driverTableContainer"] table tbody tr')
  .filter((index, el) => re.test(el.innerText))
英文:

You don't need to escape the backslash, this works (presuming your element selector works)

cy.contains(
  'div[id="driverTableContainer"] table tbody tr',
  new RegExp('\([0-9]{6}\)')
)

You don't need the g since cy.contains() passes for 1 or more occurances of the string.

Also, cy.contains() only returns the first row found. If you want multiple rows, you need to cy.get() then filter

const re = new RegExp('\([0-9]{6}\)')
cy.get('div[id="driverTableContainer"] table tbody tr')
  .filter((index, el) => re.test(el.innerText))

huangapple
  • 本文由 发表于 2023年4月17日 22:43:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76036381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定