I have a string:
" a.1.2.3 #4567 "
and I want to reduce that to just "1.2.3".
Currently using Substring() and Remove(), but that breaks if there ends up being more numbers after the pound sign.
What's the best way to go about doing this? I've read a bunch of questions on regex & string.split, but I can't get anything I try to work in VB.net. Would I have to do a match then replace using the match result?
Any help would be much appreciated.
This should work:
string input = " a.1.2.3 #4567 ";
int poundIndex = input.IndexOf("#");
if(poundIndex >= 0)
{
string relevantPart = input.Substring(0, poundIndex).Trim();
IEnumerable<Char> numPart = relevantPart.SkipWhile(c => !Char.IsDigit(c));
string result = new string(numPart.ToArray());
}
Demo
Try this...
String[] splited = split("#");
String output = splited[0].subString(2); // 1 is the index of the "." after "a" considering there are no blank spaces before it..
Here is regex way of doing it
string input = " a.1.2.3 #4567 ";
Regex regex = new Regex(#"(\d\.)+\d");
var match = regex.Match(input);
if(match.Success)
{
string output = match.Groups[0].Value;//"1.2.3"
//Or
string output = match.Value;//"1.2.3"
}
If the pound sign is the most relevant bit, rely on Split. Sample VB.NET code:
Dim inputString As String = " a.1.2.3 #4567 "
If (inputString.Contains("#")) Then
Dim firstBit As String = inputString.Split("#")(0).Trim()
Dim headingToRemove As String = "a."
Dim result As String = firstBit.Substring(headingToRemove.Length, firstBit.Length - headingToRemove.Length)
End If
As far as this is a multi-language question, here comes the translation to C#:
string inputString = " a.1.2.3 #4567 ";
if (inputString.Contains("#"))
{
string firstBit = inputString.Split('#')[0].Trim();
string headingToRemove = "a.";
string result = firstBit.Substring(headingToRemove.Length, firstBit.Length - headingToRemove.Length);
}
I guess another way using unrolled
\d+ (?: \. \d+ )+
Related
I am trying to search in titles matching entire search terms.
My example is something like below
string exampleTitle = "apple orange banana";
string term1 = "app bana";
string term2 = "bana app";
string pattern1 = #term1.Replace(" ", "*.*") + "*"; //output:app*.*bana*
string pattern2 = #term2.Replace(" ", "*.*") + "*"; //output:bana*.*app*
//now test
bool isMatch1 = Regex.IsMatch(exampleTitle , pattern1) // true
//now test
bool isMatch2 = Regex.IsMatch(exampleTitle , pattern2) // false
Thus pattern2 not match because banana comes after apple. However I need to true when matching all of words in search term without any order.
Regular expressions can be tricky here. Use this approach instead:
String exampleTitle = "apple orange banana";
String terms = "app bana";
Boolean found = true;
// let's clean things up for malformed input with RemoveEmptyEntries
foreach (String term in terms.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries))
found &= exampleTitle.Contains(term);
Using LINQ instead:
// let's clean things up for malformed input with RemoveEmptyEntries
String[] terms = terms_list.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
Boolean found = terms.All(term => exampleTitle.Contains(term));
You can use the regular expression (?=.*app)(?=.*bana) instead:
string pattern1 = "(?=.*"+term1.Replace(" ", ")(?=.*") + ")"; //output:(?=.*app)(?=.*bana)
string pattern2 = "(?=.*" + term2.Replace(" ", ")(?=.*") + ")"; //output:(?=.*app)(?=.*bana)
You can limit backtracking and forward search with this:
string pattern1 = "(?=(?>.*?"+term1.Replace(" ", "))(?=(?>.*?") + "))"; //output:(?=(?>.*?app))(?=(?>.*?bana))
string pattern2 = "(?=(?>.*?" + term2.Replace(" ", "))(?=(?>.*?") + "))"; //output:(?=(?>.*?app))(?=(?>.*?bana))
I need to true when matching all of words in search term without any order
This could be more clearly expressed as:
bool isMatch = Regex.IsMatch(exampleTitle, ".*app.*") && Regex.IsMatch(exampleTitle, ".*bana.*);
As noted in the other answer, there are non-regex ways to do substring matching that may be more appropriate.
string s = "apple]","[banana...." ;
I need to remove ( "]","[ ) and replace with "," from above string so that the output looks like below:
s = "apple,banana...."
s = s.Replace(#"\]","[\", ","); //something like this?
You need to escape the quotation marks in the string. You have tried to escape something, but \ isn't used to escape characters in a # delimited string.
In a # delimited string you use "" to escape ":
s = s.Replace(#"]"",""[", ",");
In a regular string you use \" to escape ":
s = s.Replace("]\",\"[", ",");
I assume it is a string[]?
I propose something like this:
string[] s = {"[apple]","[banana]","[orange]"} ;
string new_s = "";
foreach (string ss in s)
{
new_s += ss.Replace("[", "").Replace("]", ",");
}
//handle extra "," at end of string
new_s = new_s.Remove(new_s.Length-1);
Edit: Disregard, I misunderstood what you were trying to accomplish due to syntactical errors in your string definition.
string s = "apple]","[banana...." ;
should be:
string s = "apple]\",\"[banana....";
I'm trying to replace a string in C# with the class Regex but I don't know use the class properly.
I want replace the next appearance chain in the String "a"
":(one space)(one or more characters)(one space)"
by the next regular expression
":(two spaces)(one or more characters)(three spaces)"
Will anyone help me and give me the code and explains me the regular expresion used?
you can use string.Replace(string, string)
try this one.
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
try this one
private String StrReplace(String Str)
{
String Output = string.Empty;
String re1 = "(:)( )((?:[a-z][a-z]+))( )";
Regex r = new Regex(re1, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match m = r.Match(Str);
if (m.Success)
{
String c1 = m.Groups[1].ToString();
String ws1 = m.Groups[2].ToString() + " ";
String word1 = m.Groups[3].ToString();
String ws2 = m.Groups[4].ToString() + " ";
Output = c1.ToString() + ws1.ToString() + word1.ToString() + ws2.ToString() + "\n";
Output = Regex.Replace(Str, re1, Output);
}
return Output;
}
Using String.Replace
var str = "Test string with : .*. to replace";
var newstr = str.Replace(": .*. ", ": .*. ");
Using Regex.Replace
var newstr = Regex.Replace(str,": .*. ", ": .*. ");
i have a string Like
"Hello i want to go."
my code give "want to go."
but i need string between " i " and " to " how can i get this? my code is as below.
string[] words = Regex.Split("Hello i want to go.", " i ");
string respons = words[1];
string input = "Hello i want to go.";
Regex regex = new Regex(#".*\s[Ii]{1}\s(\w*)\sto\s.*");
Match match = regex.Match(input);
string result = string.Empty;
if (match.Success)
{
result = match.Groups[1].Value;
}
This regex will match any 'word' between 'i' (not case sensitive) and 'to'.
EDIT: changed ...to.* => to\s.* as suggested in the comments.
string input = "Hello I want to go.";
string result = input.Split(" ")[2];
If you want the word after the "i" then:
string result = input.Split(" i ")[1].Split(" ")[0];
Use
string s = "Hello i want to go.";
string[] words = s.split(' ');
string response = wor
just do it with one simple line of code
var word = "Hello i want to go.".Split(' ')[2];
//Returns the word "want"
string input = "Hello I want to go.";
string[] sentenceArray = input.Split(' ');
string required = sentenceArray[2];
Here's an example using Regex which gives you the index of each occurrence of "want":
string str = "Hello i want to go. Hello i want to go. Hello i want to go.";
Match match = Regex.Match(str, "want");
while(match.Success){
Console.WriteLine(string.Format("Index: {0}", match.Index));
match = match.NextMatch();
}
Nowhere does it say Regex...
string result = input.Split.Skip(2).Take(1).First()
it's work
public static string Between(this string src, string findfrom, string findto)
{
int start = src.IndexOf(findfrom);
int to = src.IndexOf(findto, start + findfrom.Length);
if (start < 0 || to < 0) return "";
string s = src.Substring(
start + findfrom.Length,
to - start - findfrom.Length);
return s;
}
and it can be called as
string respons = Between("Hello i want to go."," i "," to ");
it return want
what is the efficient mechanism to remove 2 or more white spaces from a string leaving single white space.
I mean if string is "a____b" the output must be "a_b".
You can use a regular expression to replace multiple spaces:
s = Regex.Replace(s, " {2,}", " ");
Something like below maybe:
var b=a.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var noMultipleSpaces = string.Join(" ",b);
string tempo = "this is a string with spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(#"[ ]{2,}", options);
tempo = regex.Replace(tempo, #" ");
You Can user this method n pass your string value as argument
you have to add one namespace also using System.Text.RegularExpressions;
public static string RemoveMultipleWhiteSpace(string str)
{
// A.
// Create the Regex.
Regex r = new Regex(#"\s+");
// B.
// Remove multiple spaces.
string s3 = r.Replace(str, #" ");
return s3;
}