search

The search task takes a regular expression and a string, then searches for the first match of the expression within the string. The task returns the index (position) where a match is found — indexing starts at zero. If no match is found, the task returns -1.

Potential use case

Use search to check whether a certain pattern exists in a string and to find its position. In conjunction with the substr method, you can use search to find and replace text in a data record.

Properties

InputTypeDescription
strStringRequired. The string to search.
regexpStringRequired. The regular expression pattern to match.
OutputTypeDescription
indexNumberThe position of the first match between the regular expression and the string. Returns -1 if not found. The first character is at position 0.

Example 1

In this example:

  • str is statically set to Hello World.
  • regexp is or.
  • The index result is 7, indicating the pattern "or" is located at position 7 in the string.
search task with str 'Hello World' and regexp 'or'
Output showing index as 7

Example 2

In this example:

  • str is Hey Dr. Livingstone.
  • regexp is \., a special character class notation indicating the match should be a period (.).
  • The index result is 6, indicating the period is located at position 6 in the string.

For more information, see Using character classes in regular expressions on MDN.

search task with str 'Hey Dr. Livingstone' and regexp '\.'
Output showing index as 6

Example 3

In this example:

  • str is Hey Judey.
  • regexp is \., indicating the match should be a period.
  • Because no period exists in the string, the index result is -1.
search task with str 'Hey Judey' and regexp '\.' — no match expected
Output showing index as -1