Game Development Reference
In-Depth Information
More information on Linq can be found online in MSDN at
http://msdn.microsoft.com/en-gb/library/bb397926.aspx .
Linq and regular expressions
Linq, of course, need not work in isolation. It can, for example, be combined with
regular expressions to extract specific string patterns from a larger string that converts
the matched results into a traversable array. This can be especially useful in processing
comma-separated value files (CSV files), for example, where data is formatted inside
a text file, each entry being separated by a comma character. Both Linq and regular
expressions can be used to read each value into a unique array element very quickly
and easily. For example, consider an RTS game where human names must be
generated for new units. The names themselves are stored in a CSV format and are
divided into two groups: male and female. On generating a character, it can be either
male or female, and an appropriate name must be assigned to them from the CSV data,
as shown in the following code sample 6-24:
01 //Generate female name
02 //Regular Expression Search Pattern
03 //Find all names prefixed with 'female:' but do not include the
prefix in the results
04 string search = @"(?<=\bfemale:)\w+\b";
05
06 //CSV Data - names of characters
07 string CSVData =
"male:john,male:tom,male:bob,female:betty,female:jessica,male:dirk
";
08
09 //Retrieve all prefixed with 'female'. Don't include prefix
10 string[] FemaleNames = (from Match m in Regex.Matches(CSVData,
search)
11 select m.Groups[0].Value).ToArray();
12
13 //Print all female names in results
14 foreach(string S in FemaleNames)
15 Debug.Log (S);
16
17 //Now pick a random female name from collection
18 string RandomFemaleName = FemaleNames[Random.Range(0,
FemaleNames.Length)];
 
Search WWH ::




Custom Search