function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vetriselvan ManoharanVetriselvan Manoharan 

Pattern and Matcher apex

Hi,

I am using pattern and matcher to [@name1]. Below is the regex
 
Pattern.compile('\\[\\@([a-z|A-Z|0-9].*?)\\]');
Using the matcher to get the values

String mentionName = pm.group(1);

Everything is works fine if it has only one [@name1] with specified pattern.

If it has more than one like [@name1] [@name2] only one value is returned. is it possible to get more than one value from the group?
Shingo YamazakiShingo Yamazaki
Dear Vetriselvan,

Does that work fine for you?
String searchStr = '[@name1] [@name2]';
Pattern pt = Pattern.compile('\\[\\@([a-z|A-Z|0-9].*?)\\]');
Matcher m = pt.matcher(searchStr);

List<String> names = new List<String>();
while (m.find()) {
    names.add(m.group());
}

System.debug(names);

 
Vetriselvan ManoharanVetriselvan Manoharan

Hi Shingo,

Thank you. But my problem is I am replacing the [@name] with some HTML and appending it.
 
fc.CommentBody = fc.CommentBody.replace('[@' + mentionName + ']', '<a href=\'' + repo.getBaseUrl() + '/' + memberC.id + '\'>@' + mentionName + '</a>');

I need to replace [@name] with a tag even if it has more than one pattern matched value
Shingo YamazakiShingo Yamazaki
Oh, OK.
Then, how about replacing the matched part every time in for loop?
 
String searchStr = '[@name1] [@name2]';
Pattern pt = Pattern.compile('\\[\\@([a-z|A-Z|0-9].*?)\\]');
Matcher m = pt.matcher(searchStr);

List<String> names = new List<String>();
String res = searchStr;
while (m.find()) {
    res = res.replace(m.group(), '<a>' + m.group(1) + '</a>');
}

// "<a>name1</a> <a>name2</a>"
System.debug(LoggingLevel.INFO, res);