本文整理汇总了C#中Regex.Split方法的典型用法代码示例。如果您正苦于以下问题:C# Regex.Split方法的具体用法?C# Regex.Split怎么用?C# Regex.Split使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Regex
的用法示例。
在下文中一共展示了Regex.Split方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RegexSplit
public static void RegexSplit()
{
string[] saExp = new string[] { "kkk", "lll", "mmm", "nnn", "ooo" };
string[] saExp1 = new string[] { "kkk", "lll:mmm:nnn:ooo" };
string[] saExp2 = new string[] { "kkk:lll", "mmm", "nnn:ooo" };
string input = "kkk:lll:mmm:nnn:ooo";
Regex regex = new Regex(":");
// Split(string)
string[] result = regex.Split(input);
Assert.Equal(saExp, result);
// A count of 0 means split all
result = regex.Split(input, 0);
Assert.Equal(saExp, result);
// public static String[] Split(string input, Int32 count); ":"
// "kkk:lll:mmm:nnn:ooo", 2
result = regex.Split(input, 2);
Assert.Equal(saExp1, result);
// public static String[] Split(string input, Int32 count, Int32 startat); ":"
// "kkk:lll:mmm:nnn:ooo", 3, 6
result = regex.Split(input, 3, 6);
Assert.Equal(saExp2, result);
}
示例2: Main
static void Main()
{
// речник който да пази търсените думи като ключове, ако има съвпадение да инкрементира
var words = new Dictionary<string, int>();
string inputWords = Console.ReadLine().ToLower();
while (inputWords != "end")
{
words.Add(inputWords, 0);
inputWords = Console.ReadLine();
}
using (StreamReader reader = new StreamReader("../../../text.txt"))
{
Regex regex = new Regex(@"[^\w+]");
//чете ред от файла и го слага в масив от думи (прави ги малки) за да обходим всяка
string line = reader.ReadLine().ToLower();
string[] wordsFromLine = regex.Split(line); // ако файла е празен ще хвърли грешка
while (line != null)
{
for (int i = 0; i < wordsFromLine.Length; i++)
{
if (words.ContainsKey(wordsFromLine[i])) //проверява за ключ
{
words[wordsFromLine[i]]++;
}
//Console.WriteLine(wordsFromLine[i]);
}
line = reader.ReadLine();
if (line != null) //проверка за празен ред
{
wordsFromLine = regex.Split(line.ToLower());
}
}
}
using (StreamWriter writer = new StreamWriter("../../results.txt"))
{
foreach (var item in words)
{
writer.WriteLine(item.Key + " - " + item.Value);
//Console.WriteLine(item.Key + " - " + item.Value);
}
}
}
示例3: BitMaskUIScenesAttribute
public BitMaskUIScenesAttribute()
{
Regex rootPath = new Regex(Regex.Escape("Assets/Scenes/")); /*+ Regex.Unescape(".+$")*/
Regex ui = new Regex(".+(Panel)|(Popup)|(Screen)\\.unity");
int size = 0;
string[] allScenes = new string[UnityEditor.EditorBuildSettings.scenes.GetLength(0)];
for(int i = 0 ; i < allScenes.Length ; i++)
{
allScenes[i] = UnityEditor.EditorBuildSettings.scenes[i].path;
allScenes[i] = rootPath.Split(allScenes[i])[1];
if(!ui.IsMatch(allScenes[i]) || !UnityEditor.EditorBuildSettings.scenes[i].enabled)
{
allScenes[i] = null;
}
else
size++;
}
scenes = new string[size];
int j = 0;
for(int i = 0 ; i < allScenes.Length ; i++)
{
if(allScenes[i] != null)
{
scenes[j] = allScenes[i];
j++;
}
}
}
示例4: Main
static void Main()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Regex splitPattern = new Regex(@"\s*\|\s*");
Dictionary<string, List<string>> winers = new Dictionary<string, List<string>>();
string command = Console.ReadLine();
while (command != "report")
{
string[] tokens = splitPattern.Split(command.Trim());
string athlete = Regex.Replace(tokens[0].Trim(), @"\s+", " ");
string country = Regex.Replace(tokens[1].Trim(), @"\s+", " ");
if (!winers.ContainsKey(country))
{
winers.Add(country, new List<string>());
}
winers[country].Add(athlete);
command = Console.ReadLine();
}
var orderedCountryData = winers
.OrderByDescending(x => x.Value.Count);
foreach (var country in orderedCountryData)
{
Console.WriteLine("{0} ({1} participants): {2} wins",
country.Key,
country.Value.Distinct().Count(),
country.Value.Count);
}
}
示例5: DefaultWordBreaks
public void DefaultWordBreaks()
{
Regex re = new Regex(@"\b");
Assert.That(re.Split("The 'quick' (\"brown\") fox\r\ncan't ju\xFEFFmp 32.3 feet,\nright?"),
Is.EqualTo(new string[] { "", "The", " ", "'", "quick", "'", " ", "(", "\"", "brown", "\"", ")", " ",
"fox", "\r\n", "can't", " ", "ju\xFEFFmp", " ", "32.3", " ", "feet", ",", "\n", "right", "?", "" }));
}
示例6: createFromString
public static RationalNumber createFromString(string initialString)
{
Regex slash = new Regex("/");
string[] two_numbers = slash.Split(initialString);
RationalNumber result = new RationalNumber(Convert.ToInt32(two_numbers[0]),
Convert.ToUInt32(two_numbers[1]));
return result;
}
示例7: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
Label4.Text = (string)Session["sid"];
Label5.Text = (string)Session["sname"];
if (!IsPostBack)
{
//Panel1.Visible = false;
//Panel2.Visible = false;
Label1.Visible = false;
//Label2.Visible = false;
//TextBox1.Visible = false;
}
Session["data"] = TextBox1.Text;
string text = TextBox1.Text;
string splitby = " ";
Regex rg = new Regex(splitby);
string[] st = rg.Split(text);
int m = st.Count();
for (int k = 0; k < m; k++)
{
if (st[k].ToString() != "")
{
DataSet da = new DataSet();
da = obj.filematching(st[k].ToString());
if (da.Tables[0].Rows.Count > 0)
{
for (int f = 0; f < da.Tables[0].Rows.Count; f++)
{
// creation of linkbutton
LinkButton linkbutton = new LinkButton();
linkbutton.Text = da.Tables[0].Rows[f]["fname"].ToString() + "<br><br>";
linkbutton.Visible = true;
linkbutton.CommandName = da.Tables[0].Rows[f]["fname"].ToString();
linkbutton.Command += new CommandEventHandler(this.link_click);
linkbutton.ID = h.ToString();
this.downloadfiles.Controls.Add(linkbutton);
linkbutton.Visible = true;
Label3.Visible = true;
Panel4.Visible = true;
Panel6.Visible = true;
h++;
}
}
else
{
MsgBox.Show("No files found");
}
}
}
}
示例8: CurrencyConversion
public string CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
{
WebClient web = new WebClient();
string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount);
string response = web.DownloadString(url);
Regex regex = new Regex(@":(?<rhs>.+?),");
string[] arrDigits = regex.Split(response);
string rate = arrDigits[3];
return rate;
}
示例9: typeText
public void typeText(string text,float delay)
{
if(label==null){
sendFinishEvent();
return;
}
label.text="";
if(delay>0)
defaultDelay=delay;
string t=text;
// t="asdb\\nasdg\\1.5hjkh\\nhjkhg";
Regex reg=new Regex(@"\\n|\\\d{1,5}\.\d{0,2}|\\\d{1,5}");
mc=reg.Matches(t);
typingText=reg.Split(t);
StopAllCoroutines();
StartCoroutine(typing());
}
示例10: FindOccurrences
static List<int> FindOccurrences(string fileName, List<string> words)
{
List<int> occurences = new List<int>();
StreamReader streamReader = null;
try
{
streamReader = new StreamReader(fileName);
string text = streamReader.ReadToEnd();
foreach (var item in words)
{
string pattern = string.Format(@"\b{0}\b", item);
Regex regex = new Regex(pattern);
occurences.Add(regex.Split(text).Length - 1);
}
}
catch (FileNotFoundException)
{
Console.WriteLine("The file {0} cannot be found", fileName);
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("The file {0} is not in this directory", fileName);
}
catch (PathTooLongException)
{
Console.WriteLine("You gave too long path");
}
catch (ArgumentNullException)
{
Console.WriteLine("Cannot use null arguments");
}
catch (ArgumentException)
{
Console.WriteLine("You cannot use blank path or special characters for a path");
}
finally
{
if (streamReader != null)
{
streamReader.Dispose();
}
}
return occurences;
}
示例11: FixContentHistory
public string FixContentHistory(ContentData myContentData, string curSnippet)
{
Regex regExp;
regExp = new Regex(" ");
foreach (string strLineVal in regExp.Split(curSnippet))
{
regExp = new Regex("=");
string[] strKeyValues;
strKeyValues = regExp.Split(strLineVal);
if ((string) (strKeyValues[0].Trim()) == "src")
{
string curStringVal = strKeyValues[1];
if (curStringVal.ToLower().IndexOf("/assets") >= 0)
{
curStringVal = (string) (curStringVal.ToLower().Replace("/assets/" + myContentData.AssetData.Id.ToLower() + myContentData.AssetData.Version.Substring(myContentData.AssetData.Version.IndexOf(".")).ToLower(), "/assetmanagement/DownloadAsset.aspx?history=true&ID=" + myContentData.AssetData.Id + "&version=" + myContentData.AssetData.Version));
curSnippet = Regex.Replace(curSnippet, strKeyValues[1], curStringVal);
}
}
}
return curSnippet;
}
示例12: DoSomething
static void DoSomething ()
{
Trace curTrace = (Trace)FindObjectOfType( typeof(Trace) );
var list = new List<WayPoint>();
var rgx = new Regex(@"\d+$");
//Selection.gameObjects doesn't hold selection order
foreach( var obj in FindObjectsOfType(typeof(WayPoint)) )
{
var wp = (WayPoint)obj;
list.Add(wp);
wp.name = rgx.Split(obj.name)[0] + wp.editorPriority.ToString("D2");
wp.trace = curTrace;
}
list.Sort( (t1, t2) => t1.editorPriority - t2.editorPriority );
//ths.wayPoints = list.Select( (v) => v.gameObject ).ToArray();
curTrace.wayPoints = list.ToArray();
}
示例13: DataBtn_Click
protected void DataBtn_Click(object sender, EventArgs e)
{
//the database data we wish to enter
//StreamReader langfile = new StreamReader("C:\\Users\\Zimmy\\Documents\\Snippit\\Languages\\" + TextBox1.Text);
StreamReader langfile = new StreamReader(Directory.GetCurrentDirectory() + @"\Languages\" + TextBox1.Text);
//Establish an SQL connection
string connectString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Zimmy\Documents\Snippit\App_Data\Database.mdf;Integrated Security=True;User Instance=True;Asynchronous Processing=true";
SqlConnection conn = new SqlConnection(connectString);
conn.Open();
string command; //the string contating the SQL command we wish to execute
SqlCommand insert; //the SQL command that will be executed
string[] cols = new string[4]; //holds each column value for each row of data
Regex splitter = new Regex(@"(\t)"); //each column of data is separated by a tab
string line; //a line of text that is read in
while((line = langfile.ReadLine()) != null)
{
cols = splitter.Split(line); //split line up by tabs (NOTE: This makes each tab into a token as well.
// Must figure out a way around this.
//Insert the row of data into the database
command = "INSERT INTO " + DropDownList2.SelectedValue + " VALUES ('" + cols[0] + "', '" + cols[2] + "', '" + cols[4] + "','" + cols[6] + "')";
insert = new SqlCommand(command, conn);
insert.ExecuteNonQuery();
}
//close the SQL connection
conn.Close();
//close the StreamReader
langfile.Close();
}
示例14: Main
static void Main()
{
const string SplitPattern = @"\s*\|\s*";
var regex = new Regex(SplitPattern);
var report = new Dictionary<string, List<string>>();
string input = Console.ReadLine();
while (input != "report")
{
string[] info = regex.Split(input.Trim());
string participant = Regex.Replace(info[0].Trim(),@"\s+", " " );
string country = Regex.Replace(info[1].Trim(), @"\s+", " ");
if (!report.ContainsKey(country))
{
report[country] = new List<string>();
}
report[country].Add(participant);
input = Console.ReadLine();
}
var output = report.OrderByDescending(r => r.Value.Count);
foreach (var data in output)
{
Console.WriteLine("{0} ({1} participants): {2} wins",
data.Key,
data.Value.Distinct().Count(),
data.Value.Count
);
}
}
示例15: BitMaskToUiScenes
public static string[] BitMaskToUiScenes(int a_bitMask)
{
Regex rootPath = new Regex(Regex.Escape("Assets/Scenes/")); /*+ Regex.Unescape(".+$")*/
Regex ui = new Regex(".+(Panel)|(Popup)|(Screen)\\.unity");
int size = 0;
string[] allScenes = new string[UnityEditor.EditorBuildSettings.scenes.GetLength(0)];
for(int i = 0 ; i < allScenes.Length ; i++)
{
allScenes[i] = UnityEditor.EditorBuildSettings.scenes[i].path;
allScenes[i] = rootPath.Split(allScenes[i])[1];
if(!ui.IsMatch(allScenes[i]) || !UnityEditor.EditorBuildSettings.scenes[i].enabled || ((1 << size) & a_bitMask) != (1 << size))
{
allScenes[i] = null;
}
else
size++;
}
string[] scenes = new string[size];
int j = 0;
for(int i = 0 ; i < allScenes.Length ; i++)
{
if(allScenes[i] != null)
{
string[] split = allScenes[i].Split('/');
string scene = split[split.Length-1];
string[] test = {"."};
scene = scene.Split(test, System.StringSplitOptions.RemoveEmptyEntries)[0];
scenes[j] = scene;
j++;
}
}
return scenes;
}