Regular Expression for Words with spaces

Problem: 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 the below ones. Nothing works

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

How do I check for words with spaces?

Solution:

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

[aA-zZ-\s] means “any character that is either an a, or a character in the range A through z (which contains several non-letters, incidentally), or a character in the range Z through \s (which is an illegal range, apparently ignored by Salesforce).

Leave a comment