Skip to main content

Cucumber Escaping Characters

Round Brackets () and Curly Brackets {} have special meaning in Cucumber Expressions. You can not use them directly. If you ever need to match () or {}, you can escape the opening ( or { with a backslash.

Cucumber Expressions won't allow us to use any other special character. For that, we have to use regular expressions.

Steps

Then I should see 5 item(s)
Then I should see 10 {what}

Step Definitions

@Then("I should see {int} item\\(s)")
public void teststep1(int i)
{
    System.out.println("value is:"+i);
}

@Then("I should see {int} \\{what}")
public void teststep2(int i)
{
	System.out.println("value 2 is:"+i);
}

Cucumber Escaping Single Special Character

Here we will remove $ and % Symbol from step.

Step

Then total of cart is $100.50
Then progress is 100%

Step Definition

@Then("total of cart is ${double}")
public void total_of_cart_is_$(Double double1) 
{
    System.out.println(double1);
}

@Then("progress is {int}%")
public void progress_is(Integer int1) 
{
    System.out.println(int1);
}

Cucumber Escaping Multiple Special Character

Cucumber Expression is fine for escaping one or two characters or matching simple text, but what if we have to escape many similar characters or have complex patterns in common steps. In that case, We have to use Regular Expressions. 

Step Definition will remove $ and € Symbol from Step.

Step

Then total of cart is $100.50
Then total of cart is €100.50

Step Definition

Escape $ and €

@Then("^total of cart is [$€]([0-9.]*)$")
public void teststep4(float i)
{
	System.out.println("value 3 is:"+i);
}

Escape any character before number

@Then("^total of cart is .([0-9.]*)$")
public void total_of_cart_is_$(Double double1) {
System.out.println(double1); 
}

Here,

  • 0-9 is for digits
  • dot . inside [] is for decimal and outside () is for any character
  • * means 0 or more
  • [] Match character in bracket
  • () is to capture value or group

Video Tutorial: Cucumber Escaping Special Characters

Submitted by tgoswami on June 2, 2021

Tarun has 11+ years of experience in Quality Assurance in different domains like Banking, E-commerce, Health and Education.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.