Skip to content

Commit

Permalink
Regex replace operations
Browse files Browse the repository at this point in the history
  • Loading branch information
poorna2152 committed Sep 30, 2024
1 parent ab9d575 commit 6ae7740
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 0 deletions.
7 changes: 7 additions & 0 deletions examples/index.json
Original file line number Diff line number Diff line change
Expand Up @@ -1201,6 +1201,13 @@
"verifyBuild": true,
"verifyOutput": true,
"isLearnByExample": true
},
{
"name": "RegExp replace operations",
"url": "regexp-replace-operations",
"verifyBuild": true,
"verifyOutput": true,
"isLearnByExample": true
}
]
},
Expand Down
23 changes: 23 additions & 0 deletions examples/regexp-replace-operations/regexp_replace_operations.bal
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import ballerina/io;

public function main() {
string creditCardNumber = "1234-5678-9876-5432";
string:RegExp pattern = re `(\d{4})-(\d{4})-(\d{4})`;
// Replaces the first occurrence of the credit card pattern with a masked representation.
string maskedCardNumber = pattern.replace(creditCardNumber, "****-****-****");
io:println(maskedCardNumber);

string xmlString = "<root>" +
"<!-- This is a comment -->" +
"<element1>Value 1</element1>" +
"<element2>Value 2</element2>" +
"<!-- Another comment -->" +
"<element3>Value 3</element3>" +
"</root>";

// Regular expression to match XML comments
string:RegExp commentPattern = re `<!--.*?-->`;
// Replaces all occurrences of XML comments with an empty string, effectively removing them.
string commentsRemoved = commentPattern.replaceAll(xmlString, "");
io:println(string `Comments removed XML: ${commentsRemoved}`);
}
12 changes: 12 additions & 0 deletions examples/regexp-replace-operations/regexp_replace_operations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# RegExp operations

The ``RegExp`` type supports a set of anguage library functions for replacing patterns in strings.

::: code regexp_replace_operations.bal :::

::: out regexp_replace_operations.out :::

## Related links
- [RegExp type](/learn/by-example/regexp-type)
- [RegExp API Docs](https://lib.ballerina.io/ballerina/lang.regexp)
- [string API Docs](https://lib.ballerina.io/ballerina/lang.string)
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
description: This BBE demonstrates how to use the regexp langlib functions relevant to regex replace operations.
keywords: ballerina, ballerina by example, bbe, regexp, RegExp, regex, regular expressions, ballerina regex functions, regexp langlib functions, replace, replaceAll
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
$ bal run regexp_replace_operations.bal
****-****-****-5432
Comments removed XML: <root><element1>Value 1</element1><element2>Value 2</element2><element3>Value 3</element3></root>

0 comments on commit 6ae7740

Please sign in to comment.