Game Development Reference
In-Depth Information
Regular expressions
Occasionally, you might need to perform more complex searches on very large
strings, such as finding all words in a string beginning with a specific letter, all
words starting with a and ending in t , and so on. In these cases, you would want the
results available in an array if there are any. You can achieve this effectively using
regular expressions ( Regex ). Regular expressions let you define a string value using
a conventional and specialized syntax, specifying a search pattern. For example,
the string [dw]ay means "ind all words that end with ay and that also begin with
either d or w . Thus, find all occurrences of either day or way". The regular expression
can then be applied to a larger string to perform a search using the Regex class.
The .NET framework provides access to regular expression searches through the
RegularExpressions namespace, as shown in the following code sample 6-19:
01 //-------------------------------------------------------
02 using UnityEngine;
03 using System.Collections;
04 //Must include Regular Expression Namespace
05 using System.Text.RegularExpressions;
06 //-------------------------------------------------------
07 public class RGX : MonoBehaviour
08 {
09 //Regular Expression Search Pattern
10 string search = "[dw]ay";
11
12 //Larger string to search
13 string txt = "hello, today is a good day to do things my way";
14
15 // Use this for initialization
16 void Start ()
17 {
18 //Perform search and get first result in m
19 Match m = Regex.Match(txt, search);
20
21 //While m refers to a search result, loop
22 while(m.Success)
23 {
24 //Print result to console
25 Debug.Log (m.Value);
26
27 //Get next result, if any
28 m = m.NextMatch();
29 }
 
Search WWH ::




Custom Search