SplitString or SubString or? - c#

Is there (.NET 3.5 and above) already a method to split a string like this:
string str = "{MyValue} something else {MyOtherValue}"
result: MyValue , MyOtherValue

Do like:
string regularExpressionPattern = #"\{(.*?)\}";
Regex re = new Regex(regularExpressionPattern);
foreach (Match m in re.Matches(inputText))
{
Console.WriteLine(m.Value);
}
System.Console.ReadLine();
dont forget to add new namespace: System.Text.RegularExpressions;

You can use regular expressions to do it. This fragment prints MyValue and MyOtherValue.
var r = new Regex("{([^}]*)}");
var str = "{MyValue} something else {MyOtherValue}";
foreach (Match g in r.Matches(str)) {
var s = g.Groups[1].ToString();
Console.WriteLine(s);
}

MatchCollection match = Regex.Matches(str, #"\{([A-Za-z0-9\-]+)\}", RegexOptions.IgnoreCase);
Console.WriteLine(match[0] + "," + match[1]);

Something like this:
string []result = "{MyValue} something else {MyOtherValue}".
Split(new char[]{'{','}'}, StringSplitOptions.RemoveEmptyEntries)
string myValue = result[0];
string myOtherValue = result[2];

Related

Need write # under each tweet C#

Apologies in advance, English is not my first language.
I need to write under each tweet: #..... I am using Regex.IsMatch, but console write all tweets.
var tweet = tweets[i].Text;
var CreatedDate = tweets[i].CreatedDate.ToString("F");
var TweetTime = DateTime.Parse(CreatedDate);
var age = DateTime.Now.Subtract(TweetTime);
Console.WriteLine(tweet);
Console.WriteLine($"с момента создания прошло {age} времени");
Console.WriteLine();
var pattern = #"#\D*";
foreach(var sharp in tweet)
{
if (Regex.IsMatch(tweet, pattern, RegexOptions.IgnoreCase))
Console.WriteLine(sharp);
}
I don't know what you're trying to implement, but i see why your not getting the hashtag to print. Regex.IsMatch doesn't change the text it just evaluates it. Try something like this.
var pattern = #"#\D*";
foreach (var sharp in tweet)
{
var match = Regex.Match(pattern, sharp);
if (match.Success)
Console.WriteLine(Regex.Replace(sharp, match.Value, "#" + match.Value, RegexOptions.Singleline));
else
Console.WriteLine(sharp);
}
Thank's all
Right anwsers is next:
string pattern = #"\s*#(\w+)\s*";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(tweet);
if (matches.Count > 0)
{
foreach (Match match in matches)
Console.WriteLine(" " + match.Value);
}
Thanks for #M. Green

C# Regex extract certain digits from a number

I am trying to extract the digits from 10:131186; and get 10131186 without the : and ;.
What is the Regex pattern I need to create?
var input = "10:131186;";
string pattern = ":(.*);";
Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Value);
With the above code, I am getting :131186; instead of 10121186.
Why you need to use Regex. It's slower than using string.Replace method
string input = "10:131186;";
input = input.Replace(":", "");
input = input.Replace(";", "");
Console.WriteLine(input);
You can try using Regex.Replace:
var input = "10:131186;";
string pattern = #"(\d+):(\d+);";
string res = Regex.Replace(input, pattern, "$1$2");
Console.WriteLine(res);
and you can also use Split with Join:
var input = "10:131186;";
Console.WriteLine(string.Join("", input.Split (new char[] { ':', ';' }, StringSplitOptions.RemoveEmptyEntries)));
Please try this..
string input = "10:131186;";
input = input.Replace(":", String.Empty).Replace(";", string.Empty);
Just print the group index 1.
var input = "10:131186;";
string pattern = ":(.*);";
Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Value[1]);
or use assertions.
var input = "10:131186;";
string pattern = "(?<=:).*?(?=;)";
Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Value);
You could use the pattern \\d+ to match digits in the string and concatenate them into a single string.
using System;
using System.Text;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string input = "10:131186;";
MatchCollection mCol = Regex.Matches(input, "\\d+");
StringBuilder sb = new StringBuilder();
foreach (Match m in mCol)
{
sb.Append(m.Value);
}
Console.WriteLine(sb);
}
}
Results:
10131186
Demo

Regular Expression in c# to find letter then \ with capital letter for letter and Shift press form of other charecter?

I want to convert a string like
m\anoj ku\mar m\a\noj
to
Manoj kUmar MAnoj
how can i do this using c#
string convert(string text)
{
string pattern = #"$1\\";
string repPattern =#"";
string returnText = Regex.Replace(text, repPattern, pattern);
return returnText;
}
What is assigneed to repPattern ? to get result
Try following:
var input = #"m\anoj ku\mar m\a\noj";
var pattern = new Regex(#"([a-z])\\");
var replaced = pattern.Replace(input, m => m.Groups[1].ToString().ToUpper());
Console.WriteLine(replaced);
UPDATE
Map digits to shift-pressed form:
string text= #"m\an1oj ku\mar m\a\no9j";
char[] shiftPressForms = ")!##$%^&*(".ToCharArray();
Regex pattern = new Regex(#"([a-z])\\");
Regex pattern_digit = new Regex(#"\d");
string replaced = pattern.Replace(text, m => m.Groups[1].ToString().ToUpper());
replaced = pattern_digit.Replace(replaced, m => shiftPressForms[int.Parse(m.Value)].ToString());
Console.WriteLine(replaced);

Remove specific symbol from string

I have different string that starts and ends with { } like so {somestring}. I want to remove the delimiters from the string so that it shows somestring only. I can't do anything that counts the letters because I don't always know the length of the string.
Maybe this will help. Here is the code, somewhere here I want to delete the delimiters.
private static MvcHtmlString RenderDropDownList(FieldModel model)
{
ISerializer serializer = new SerializeJSon();
var value = "";
var tb1 = new TagBuilder("select");
tb1.MergeAttribute("id", model.QuestionId);
tb1.MergeAttribute("name", model.QuestionId);
tb1.MergeAttributes(GetHtmlAttributes(model.HtmlAttributes));
tb1.AddCssClass("form-field");
var sb = new StringBuilder();
MatchCollection matches = RegexHelper.GetBetweenDelimiter(model.FieldValues, "{", "}");
foreach (Match match in matches)
{
var o = match; //Solution var o = match.toString();
var tb2 = new TagBuilder("option");
//Solution string newString = o.trim(new [] { "{","}"});
tb2.SetInnerText(o.ToString()); //Solution tb2.SetInnerText(newString);
sb.Append(tb2.ToString(TagRenderMode.Normal) + "\n");
}
tb1.InnerHtml = sb.ToString();
return new MvcHtmlString(tb1.ToString(TagRenderMode.Normal));
}
string newString = originalString.Trim(new[] {'{', '}'});
Can you use Replace
string somestring = somestring.Replace("{","").Replace("}","");
Alternatively, you can use StartsWith and EndsWith which will only remove from the beginning and the end of the string, for example:
string foo = "{something}";
if (foo.StartsWith("{"))
{
foo = foo.Remove(0, 1);
}
if (foo.EndsWith("}"))
{
foo = foo.Remove(foo.Length-1, 1);
}
You could use replace e.g.
string someString = "{somestring}";
string someOtherString = someString.Replace("{","").Replace("}","");

Get everything before the second given character using Regular Expression

I have a list of strings like
[ABC].[XXX].sdfnwoaenwaf
[ABC].[XXX].sdfnwoaenwaf
[ABC].[XX1].sdfnwoaenwaf
[ABC].[XX1].sdfnwoaenwaf
[AB1].[XX3].sdfnwoaenwaf
[AB2].[XX1].sdfnwoaenwaf
How can I get everything before the second dot? e.g. [ABC].[XXX] for the first one.
(.*)\. is the regex you need. You may test on http://regexhero.net/tester/
You could try a regex or use the LastIndexOf method of the String class or the Split method of the String class.
Regex
var toMatch = "[ABC].[XXX].sdfnwoaenwaf";
var pattern = new Regex("(.*?\\..*?)(:?\\.)");
var beforeSecondDot = pattern.Match(toMatch);
var stringBeforeSecondDot = beforeSecondDot.Groups[1].Value;
String.LastIndexOf
var toMatch = "[ABC].[XXX].sdfnwoaenwaf";
var indexOfLastDot = toMatch.LastIndexOf('.');
var beforeSecondDot = toMatch.Substring(0, indexOfLastDot);
String.Split
var toMatch = "[ABC].[XXX].sdfnwoaenwaf";
var parts = toMatch.Split('.');
var beforeSecondDot = String.Join(".", parts.Take(2));
string x = "[AB2].[XX1].sdfnwoaenwaf";
Regex regex = new Regex("([^.]+\\.[^.]+)\\.");
Match match = regex.Match(x);
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
}
Output:
[AB2].[XX1]
List<string> finalStrings = new List<string>();
List<string> strings = new List<string>();
strings.Add("[ABC].[XXX].sdfnwoaenwaf");
strings.Add("[ABC].[XXX].sdfnwoaenwaf");
strings.Add("[ABC].[XX1].sdfnwoaenwaf");
strings.Add("[ABC].[XX1].sdfnwoaenwaf");
strings.Add("[ABC].[XX3].sdfnwoaenwaf");
strings.Add("[ABC].[XX1].sdfnwoaenwaf");
foreach (var item in strings)
{
Regex rex = new Regex("(.*)\\.");
string[] y = rex.Split(item);
finalStrings.Add(y[1]);
}

Categories

Resources