For the given text obtained from a text area field:
Apex script unhandled exception by user/organization: xxx/xxx
Visualforce Page: /apex/pagename
caused by: System.NullPointerException: Attempt to de-reference a null >object
trace line 1
trace line 2
I want to match and capture
Visualforce Page: /apex/pagename
Note: This line can be anything but will always be a single line of text with followed by one or more \n then the line starting with caused by
I have tried the following regex at regex101 and it shows the FULL MATCH being "Visualforce Page: /apex/pagename "
In salesforce I am using the following pattern
(?im).*(?=\\n*caused by.*)
Which in regex101 grabs the first non empty line prior to the "caused by"
Now when I run the following code I get a true value debugged
System.debug(
Pattern.compile('(?m).*(?=\\n*caused by.*)')
.matcher(t).find()
);
But I cannot seem to get the actual text of the match.....
I am using the following code and get the following debug
System.debug(t);
Pattern p = Pattern.compile('(?im).*(?=\\n*caused by.*)');
Matcher m = p.matcher(t);
while(m.find()){
System.debug(m.groupCount());
System.debug(m.start());
System.debug(m.end());
System.debug(m.group(0));
}
Note: I also tried the following pattern with same results (?im)(.*)(?=\\n*caused by)
Update -- Still not working but
I added a check for charAt
to see what group 1 was returning when I used the pattern: (?im)(.*)(?=\\n*caused by.*)
doing a m.group(1).length
gets 0
so I changed the pattern to (?im).*[^\\n](?=\\n*caused by.*)
doing a m.group(0).length
gets 0 for the first find and 1 for the second find. The second find is char(13)
System.debug(m.groupCount());
String x = m.group(0);
System.debug(x);
System.debug(x.length());
System.debug(x.charAt(0));
trying to do the pattern (?im).*[^\\r\\n](?=\\n*caused by.*)
results in no matches...
When copied and pasted into regex101 it works fine but seems apex is having issues. I cannot seem to get anything but the CR or LF back and when I try to exclude both I get no matches
BUT If I do this before the matching process it works fine:
t = t.replaceAll('\\r','');
I am not the best at regex so I cannot seem to get it to exclude the \r
as when I include [^\\r\\n]
when not replacing the \r
I get no matches
I am not the best at regex and pattern and matcher so any help on getting the matched text would be great
m.find();
and thenm.group()
. Are you using the Salesforce cli to execute an anonymous block? What happens if you execute via anonymous window from a dev console?\\r
to the look forward I get no matches. Still stuck but I will update my question with the findings...\\n
or chr(13) if I do exclude\\n
. Trying to exclude both[^\\r\\n]
results in no match. Yet the operation works in all the regex testers I have found.....replace('\r','')
on the queried string makes it work but I would prefer to be able to do this in regex rather than another line of code to make it work....maybe its not possible.