function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ram Manohar GRam Manohar G 

REGEX- APEX Regualr expression allow selected charedcters only in string anywhere

Hi How to write Regex that should allow only a-z,A-Z,. , &,-, and whitespace in a string. I written below one

[a-zA-Z\\.\\&\\-\\ ]

The above one working if string only starts with alphabets (eg:sfdc.) , not working if start with other charecters(eg: &ab.)

Please post your answer. Thanks

Nayana KNayana K
String message = '&sfdc.';
String regex = '[a-zA-Z\\.\\&\\-\\ ]+';
Pattern regexPattern = Pattern.compile(regex);
Matcher regexMatcher = regexPattern.matcher(message);
System.debug(System.LoggingLevel.INFO, regexMatcher.matches());

This is working for me.