React Native Requires Chilkat v11.1.0+
React Native
Regular Expression Replace Full Matches
See more Regular Expressions Examples
Demonstrates replacing the full matches of a regular expression.Note: Chilkat uses PCRE2. See PCRE2 Regular Expressions
Also see: PCRE2 Performance
Chilkat React Native Downloads
import { JsonObject, StringBuilder } from '@chilkat/react-native'
function chilkatExample() {
const subject = 'John Anders, +_+_+ Mary Robins $$$$';
const pattern = '\\w+\\s+\\w+';
const sb = new StringBuilder();
sb.append(subject);
const json = new JsonObject();
json.emitCompact = false;
const timeoutMs = 2000;
let numMatches = sb.regexMatch(pattern, json, timeoutMs);
if (numMatches < 0) {
// Probably an error in the regular expression.
// Suggestion: Use AI to help create and/or diagnose regular expressions.
console.log(sb.lastErrorText);
return;
}
// Examine the matches:
console.log(json.emit());
// {
// "match": [
// {
// "group": [
// {
// "cap": "John Anders",
// "idx": 0,
// "len": 11
// }
// ]
// },
// {
// "group": [
// {
// "cap": "Mary Robins",
// "idx": 19,
// "len": 11
// }
// ]
// }
// ]
// }
const sbTemp = new StringBuilder();
let i = 0;
numMatches = json.sizeOfArray('match');
while (i < numMatches) {
json.i = i;
// The full match is always in group 0.
sbTemp.clear();
json.stringOfSb('match[i].group[0].cap', sbTemp);
// Indicate that we wish to replace the full match with it's value converted to uppercase.
sbTemp.toUppercase();
json.updateSb('match[i].group[0].rep', sbTemp);
i++;
}
// The JSON now has replacement strings:
console.log(json.emit());
// {
// "match": [
// {
// "group": [
// {
// "cap": "John Anders",
// "idx": 0,
// "len": 11,
// "rep": "JOHN ANDERS"
// }
// ]
// },
// {
// "group": [
// {
// "cap": "Mary Robins",
// "idx": 19,
// "len": 11,
// "rep": "MARY ROBINS"
// }
// ]
// }
// ]
// }
// Call RegexReplace to update the StringBuilder with the replacements.
try {
sb.regexReplace(json);
} catch {
console.log(sb.lastErrorText);
return;
}
console.log('Result after doing replacements:');
console.log(sb.getAsString());
// Result after doing replacements:
// JOHN ANDERS, +_+_+ MARY ROBINS $$$$
}