In Apex we can access a field using the dot notation
Example : Owner.Name
I am looking for a regex to validate that notation
I come up we the regex below
String validateDotNotation='([a-zA-Z]([a-zA-Z1-9]|[a-zA-Z1-9]_[a-zA-Z1-9])*[a-zA-Z1-9](__[rRcC])?\\.)*([a-zA-Z]([a-zA-Z1-9]|[a-zA-Z1-9]_[a-zA-Z1-9])*[a-zA-Z1-9](__[cC])?)'
Some explanations
[a-zA-Z] : validate the first char must be alphabetic upper or lower case
[a-zA-Z1-9] : validate char must be alphanumeric
[a-zA-Z1-9]_[a-zA-Z1-9] : validate _ must not be two consecutive _
[a-zA-Z1-9]|[a-zA-Z1-9]_[a-zA-Z1-9] : validate middle field name chars can be alphanumeric & non consecutive _
[a-zA-Z]([a-zA-Z1-9]|[a-zA-Z1-9]_[a-zA-Z1-9])*[a-zA-Z1-9] : validate a field name
(__[rRcC])? : custom or relationship field ending
(__[cC])? : custom field ending
Salesforce naming rules for a field API Name
Can you tell me if it's correct or if there is a better way to do it ?
Best Answer
Regular expressions do have their uses, but I find myself trying to avoid using regex if I can.
I think there's a better solution in your case.
Using Apex, you can pull the fields from an object (any sObject).
Using this approach, you can do something that your regex will never be able to, you can verify that the given field name is actually a field on your target object. Given the line of code above, and assuming you have a variable called
fieldName
...It gets a bit more involved if you want to do this for related fields, but using
String.split('.')
,Schema.getGlobalDescribe()
, andSchema.DescribeFieldResult.getReferenceTo()
, would accomplish what you're looking to do here.