2

If I try and test the same string it works fine in all the online regex testers but its not working in console. throwing me NOT FOUND Error. Can anyone guide me.

string str='this is a test [12312] email subject [dfasdfa]';
Pattern patt = Pattern.compile('\\[([0-9]*?)\\]');
Matcher match = patt.matcher(str);
system.debug('mat'+match.group(1));

Regex Tester : http://regexr.com/

3

You have to use find method of the Matcher class.

In my observation, if you use m.find() function it search for the string based on your pattern then returns true and you will get the value in debug

string str='this is a test [12312] email subject [dfasdfa]';
Pattern patt = Pattern.compile('\\[([0-9]*?)\\]');
Matcher match = patt.matcher(str);
if (match.find()) 
{
   system.debug(match.group(1)); 
}

If you run this code you will get matched string i.e [12312]..

If you don't use m.find() function then pattern will never search for string that you are looking for and you will get nothing

string str='this is a test [12312] email subject [dfasdfa]';
Pattern patt = Pattern.compile('\\[([0-9]*?)\\]');
Matcher match = patt.matcher(str);
system.debug(match.group(1)); 

If you run this code you will get no match found..

matches() method

The Matcher class Javadoc states, "The matches() method attempts to match the entire input sequence against the pattern." Therefore, your pattern must match the entire input sequence.

The find() method

As mentioned earlier, another approach is to use the find method of the Matcher class. The find method does not require your pattern to match the entire String.

Documentation

| improve this answer | |
0

My regex works fine. I havent checked the condition whether the regex string is true or false, once its true i am able to get the Substring.

if (m.find()) 
{
   system.debug(m.group(1)); 
}
| improve this answer | |
  • 1
    If someone else has already answered your question, you should accept their answer as correct rather than posting the same answer yourself. – Adrian Larson Mar 6 '16 at 17:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.