[SalesForce] Regular Expression for words with spaces

I want to check for the following strings using regExpression:

1) Main-xxxxx-Accepted
2) Main-xxx xxx-Accepted

I used the below

String regEx = 'Main-[aA-zZ-]*-Accepted';

Pattern.matches(regEx,'Main-SUBMITTED-Accepted')); results in **TRUE**

It works fine for Main-SUBMITTED-Accepted. But it fails for a word with spaces (non submitted)

Pattern.matches(regEx,'Main-NOT SUBMITTED-Accepted'));  results in **FALSE**

I tried these. Nothing works

String regEx = 'Main-[aA-zZ-\\s]*-Accepted';
String regEx = 'Main-[aA-zZ-\s]*-Accepted';

How do I check for words with spaces?

Best Answer

Try with this:

String regEx = 'Main-[a-zA-Z0-9- ]*-Accepted';

Copy and Paste Code:

String regEx = 'Main-[a-zA-Z0-9- ]*-Accepted';
System.debug(' @@@@@@ Main-NOT SUBMITTED-Accepted '+Pattern.matches(regEx,'Main-NOT SUBMITTED-Accepted'));
System.debug(' @@@@@@ Main-NOT-SUBMITTED-Accepted '+Pattern.matches(regEx,'Main-NOT-SUBMITTED-Accepted'));
System.debug(' @@@@@@ Main-NOT$-SUBMITTED-Accepted '+Pattern.matches(regEx,'Main-NOT$-SUBMITTED-Accepted'));
System.debug(' @@@@@@ Main45NOT-SUBMITTED-Accepted '+Pattern.matches(regEx,'Main45NOT-SUBMITTED-Accepted'));
Related Topic