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
Ravi Dutt SharmaRavi Dutt Sharma 

Parse a string

Hi,

Need inputs on how to parse below string and extract all the relevant information such as Source, Name etc.

Source: Web Visitor 
Name: Ravi Sharma 
Age of primary applicant: 9 


Email: test@yahoo.com 
Phone: 1234567 
Address: 10th Street 
City: Woodstock 
State: GA 
Comments: Test Comments 
Best Answer chosen by Ravi Dutt Sharma
Suraj GharatSuraj Gharat
You may use regex here, as below.
 
// You input. I was not sure about line break character, but similar logic can be used
string input = 'Source: Web Visitor \n'+
'Name: Ravi Sharma \n'+
'Age of primary applicant: 9 \n\n\n'+
'Email: test@yahoo.com \n'+
'Phone: 1234567 \n'+
'Address: 10th Street ';

// split whole input into lines
string[] lines = input.split('[\n]+');

string regex = '([^:]+):([^:]+)';

Pattern MyPattern = Pattern.compile(regex);

// Apply regex to every line
for(string inputLine : lines){
	matcher myMatcher = myPattern.matcher(inputLine.trim());
	if(myMatcher.matches() && myMatcher.hitEnd() && myMatcher.groupCount() == 2){
		system.debug('**** Match :'+myMatcher.group(1).trim() + '=>'+myMatcher.group(2).trim());
	}
	else{
		system.debug('No match: line :'+ inputLine);
	}
}

Hope this helps.

All Answers

Suraj GharatSuraj Gharat
You may use regex here, as below.
 
// You input. I was not sure about line break character, but similar logic can be used
string input = 'Source: Web Visitor \n'+
'Name: Ravi Sharma \n'+
'Age of primary applicant: 9 \n\n\n'+
'Email: test@yahoo.com \n'+
'Phone: 1234567 \n'+
'Address: 10th Street ';

// split whole input into lines
string[] lines = input.split('[\n]+');

string regex = '([^:]+):([^:]+)';

Pattern MyPattern = Pattern.compile(regex);

// Apply regex to every line
for(string inputLine : lines){
	matcher myMatcher = myPattern.matcher(inputLine.trim());
	if(myMatcher.matches() && myMatcher.hitEnd() && myMatcher.groupCount() == 2){
		system.debug('**** Match :'+myMatcher.group(1).trim() + '=>'+myMatcher.group(2).trim());
	}
	else{
		system.debug('No match: line :'+ inputLine);
	}
}

Hope this helps.
This was selected as the best answer
Ravi Dutt SharmaRavi Dutt Sharma
Thanks Suraj, this works. On line 10, why did you use [\n]+ to split instead of just using \n
Suraj GharatSuraj Gharat
I see in the input, there could be multiple line breaks between two lines, and thus I used "[\n]+" to match one or more line breaks.