3

I have a string where object names are enclosed in <>. Something like this->

         String source = 'I have <name> and <id>'; 

Object name is stored in another String ->

          String objectName = 'Contact'; 

I need to get the fields like this->

          String fields = 'name,id';    

How to achieve this?

So that I can use it in query ->

           String query = 'Select '+fields+' from '+objectName;
           List<sObject> myList= Database.Query(query);

2 Answers 2

0

There may be more efficient ways of doing this, but how about something like:

String source = 'I have <name> and <id>';     
Matcher m = Pattern.compile('(?m)<.*?>').matcher(source);
while (m.find()) 
{
    System.debug( source.substring(m.start()+1, m.end()-1 ) );
}
3
  • yeah it worked :) Commented Nov 6, 2013 at 5:51
  • But its not working when I am using like this: String source = 'I have {account.name} and {id}'; Matcher m = Pattern.compile('(?m){.*?}').matcher(source); while (m.find()) { System.debug('Result::'+source.substring(m.start()+1, m.end()-1 ) ); } Commented Nov 6, 2013 at 7:21
  • Yeah, think you'll need a couple of slashes in there for that, try '(?m)\\{.*?\\}' as your pattern. Commented Nov 6, 2013 at 8:06
3

You could use a regular expression to realize the list of fields:

Matcher m = Pattern.compile('<([a-zA-Z0-9_]+?)>').matcher(source);
Set<String> fields = new Set<String>();
for(Integer groupNum = 1; groupNum < m.groupCount(); groupNum++) {
    fields.add(m.group(groupNum));
}
fields.retainAll(Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap().keySEt());
String queryFields = String.join(new List<String>(fields), ',');
1
  • Did you try this code @sfdcfox? I can't seem to get it to work.. Commented Nov 6, 2013 at 8:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .