[SalesForce] Regular Expression is not working in apex

I'm trying to match a string with Pattern/Matcher. I want to extract sub string from a string. could anybody give me the solution to match the following sub string?

<!-- if(Rajendra Patel == 'Rajendra Patel'){
---
<br />
User Name : Rajendra Patel
<br />
Organization Name : VersatileCapitalist Software Inc
<br />
Date : 27/01/2015
<br />
Time : 5:15 PM
<br />
Date Time : 27/01/2015 5:15 PM
<br />
Year : 2015
<br />
Month : 1
<br />
Next Day(Tomorrow): 28/01/2015
<br />
LastDay(Yesterday) : 26/01/2015
<br />
} --> 

The following regular expressions is working fine in javascript and java but it is not working in apex.
working in javascript:
<!([-]*)(\s+)(If|if)(?:\n|.)*\}\s-->
Not working in apex:
<!([-]*)(\\s+)(If|if)(?:\\n|.)*\\}\\s-->

Best Answer

The APEX compiler works very different for RegEx than what you're used to with JS. First, none of the Global Switches are supported. Some things need to have additional escapes and pretty much everything needs to be in capture groups. That's because Apex uses different methods of it's own in the matcher class to provide this kind of functionality.

I believe you'll find that your (If|if) needs to be replaced with an ((If)|(if)).

With the way Apex works, you'll probably want to remove what appears to be a non-capture group: (?:\n|.)

To get you to the start of the name, I'd expect your pattern to look something more like the following:

(((<!)(\-*)(\\s*)((If)|(if)))\()

I recommend you go to http://regexr.com/ , paste in the string <!-- if(Rajendra Patel == 'Rajendra Patel'){ assuming that's what you want to match against, in the text box below (after clearing it), then work out the pattern for yourself.

I'd also suggest you think in terms of combining RegEX with other string methods to strip away things that are easy to find that you know you don't need or want. This will make your task easier.

For example, once you find your opening and closing parens inside the lesser and greater than symbols, you can strip away what's outside of them. You could also split the string based on finding the ==. Be smart and don't make this more complex than it has to be.

Related Topic