I have a text like this
#-cmd1-# Hakona Matata #-cmd2-#
I want to get all values that is like this #-TEXT-#
Here's the code I use, but it works only when there's one occurrence
var text = "#-adsfree-# hakona matata #-adsbottom-#";
Regex regex = new Regex("#-(.*)-#");
var v = regex.Match(text);
string s = v.Groups[1].ToString();
I'm guessing that you might be designing an expression, maybe similar to:
(?<=#-)\b(\w+)\b(?=-#)
Test
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = #"(?<=#-)\b(\w+)\b(?=-#)";
string input = #"#-adsfree-# hakona matata #-adsbottom-#";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
The expression is explained on the top right panel of this demo if you wish to explore/simplify/modify it.
Related
I would like to have a regualr expression for the string where output would be like:
CP_RENOUNCEABLE
CP_RIGHTS_OFFER_TYP
CP_SELLER_FEED_SOURCE
CP_SELLER_ID_BB_GLOBAL
CP_PX
CP_RATIO
CP_RECLASS_TYP
I tried using regex with
string pattern = #"ISNULL(*)";
string strSearch = #"
LTRIM(RTRIM(ISNULL(CP_RENOUNCEABLE,'x2x'))), ISNULL(CP_RIGHTS_OFFER_TYP,-1), LTRIM(RTRIM(ISNULL(CP_SELLER_FEED_SOURCE,'x2x'))),
LTRIM(RTRIM(ISNULL(CP_SELLER_ID_BB_GLOBAL,'x2x'))),ISNULL(CP_PX,-1), ISNULL(CP_RATIO,-1), ISNULL(CP_RECLASS_TYP,-1);
string pattern = #"ISNULL(*\)";
foreach (Match match in Regex.Matches(strSearch, pattern))
{
if (match.Success && match.Groups.Count > 0)
{
var text = match.Groups[1].Value;
}
}
My guess is that we'd be having a comma after our desired outputs listed in the question, which then this simple expression might suffice,
(CP_[A-Z_]+),
Demo 1
If my guess wasn't right, and we would have other chars after that such as an space, we can add a char class on the right side of our capturing group, such as this:
(CP_[A-Z_]+)[,\s]
and we would add any char that might occur after our desired strings in [,\s].
Demo 2
Test
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = #"(CP_[A-Z_]+),";
string input = #"LTRIM(RTRIM(ISNULL(CP_RENOUNCEABLE,'x2x'))), ISNULL(CP_RIGHTS_OFFER_TYP,-1), LTRIM(RTRIM(ISNULL(CP_SELLER_FEED_SOURCE,'x2x'))),
LTRIM(RTRIM(ISNULL(CP_SELLER_ID_BB_GLOBAL,'x2x'))),ISNULL(CP_PX,-1), ISNULL(CP_RATIO,-1), ISNULL(CP_RECLASS_TYP,-1);";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
Edit:
For capturing what is in between ISNULL and the first comma, this might work:
ISNULL\((.+?),
Demo 3
I have a formula in excel which upon reading from C# code looks like this
"=HYPERLINK(CONCATENATE(\"https://abc.efghi.rtyui.com/#/wqeqwq/\",#REF!,\"/asdasd\"), \"View asdas\")"
I want to use regex to fetch the URL from this string, i.e.
https://abc.efghi.rtyui.com/#/wqeqwq/#REF!/asdasd
The url can be different but the format of the formula will remain the same.
"=HYPERLINK(CONCATENATE(\"{SOME_STRING}\",#REF!,\"{SOME_STRING}\"), \"View asdas\")"
Try it like this:
(?<=HYPERLINK\(CONCATENATE\(")[^"]+
Demo
The positive lookbehind allows us to skip part in-front of the URL from the full match.
If you have an arbitrary number of whitespace in-between add some \s*, e.g. see this example that also shows the escaped = at the beginning of the string.
Sample Code:
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = #"(?<=HYPERLINK\(CONCATENATE\("")[^""]+";
string input = #"=HYPERLINK(CONCATENATE(""https://abc.efghi.rtyui.com/#/wqeqwq/"",#REF!,""/asdasd""), ""View asdas"")";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
Addendum: Here is another technique that uses capturing groups and regex Replace to extract the resulting URL string (after CONCATENATE would have happened):
^\=HYPERLINK\(CONCATENATE\("([^"]+)",([^,]+),"([^"]+)".*$
Demo2
string pattern = #"^\=HYPERLINK\(CONCATENATE\(""([^""]+)"",([^,]+),""([^""]+)"".*$";
string substitution = #"$1$2$3";
string input = #"=HYPERLINK(CONCATENATE(""https://abc.efghi.rtyui.com/#/wqeqwq/"",#REF!,""/asdasd""), ""View asdas"")";
Regex regex = new Regex(pattern);
string result = regex.Replace(input, substitution, 1);
You can extract the URL from the formula using capturing groups in regular expression as given below:
string inputString = "=HYPERLINK(CONCATENATE(\"https://abc.efghi.rtyui.com/#/wqeqwq/\",#REF!,\"/asdasd\"), \"View asdas\")";
string regex = "CONCATENATE\\(\"([\\S]+)\",#REF!,\"([\\S]+)\"\\)";
Regex substringRegex = new Regex(regex, RegexOptions.IgnoreCase);
Match substringMatch = substringRegex.Match(inputString);
if (substringMatch.Success)
{
string url = substringMatch.Groups[1].Value + "#REF!" + substringMatch.Groups[2].Value;
}
I have defined two capturing groups in my regular expression. One for extracting part of the URL before #REF! and the other for extracting part of the URL after #REF!. Then I am concatenating all the extracted parts with #REF! to get the final URL.
I have a long text which contains strings like these:
...
1.1SMITH/JOHN 2.1SMITH/SARA
...
1.1Parker/Sara/Amanda.CH07/Elizabeth.IN03
...
Is there any regular expression in C# which can match these names. The clue is to search for [A-Z] which has separated by '/'.
You can try this:
[a-zA-Z\/]+
Explanation
c# sample:
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = #"[a-zA-Z\/]+";
string input = #"...
1.1SMITH/JOHN 2.1SMITH/SARA
...
1.1Parker/Sara/Amanda.CH07/Elizabeth.IN03";
foreach (Match m in Regex.Matches(input, pattern))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
You can test the working c# sample here
You can use
[a-z\/]+
which matches any combination of characters and slashes (see Regex101).
Make sure you are matching case-insensitive.
var expression = new Regex(#"[a-z\/]+", RegexOptions.IgnoreCase);
var names = expression.Matches(theText, expression);
Do you want to capture any [A-Za-z] which has a previous char or next char equals '/'?
Try this:
(?<=\/)[A-Za-z]+|[A-Za-z]+(?=\/)
I'm building a regex and I'm missing something as it's not working properly.
my regex logic is trying to look for anything that has #anychars# and return the number of matches on the sentence and not a single match.
Here are a few examples
1- #_Title_# and #_Content_# should return two matches: #_Title_# and #_Content_#.
2- Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_# should return 3 matches: #_TemplateName_# #_Full_Product_Name_# and #_Short_Description_#
and so on. Here is what my regex looks like: ^(.*#_.*_#.*)+$
any thoughts on what I'm doing wrong?
Something as simple as:
#.*?#
Or:
#_.*?_#
If you are trying to match the underscores too (it wasn't clear in the original version of the question). Or:
#_(.*?)_#
Which makes it easier to extract the token between your #_ and _# delimiters as a group.
Should work. The *? is key. It's non-greedy. Otherwise you match everything between the first and last #
So for example:
var str = "Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_#";
var r = new Regex("#_(.*?)_#");
foreach (Match m in r.Matches(str))
{
Console.WriteLine(m.Value + "\t" + m.Groups[1].Value);
}
Outputs:
#_TemplateName_# TemplateName
#_Full_Product_Name_# Full_Product_Name
#_Short_Description_# Short_Description
Try this :
string[] inputs = {
"#Title# and #Content#",
"Product #TemplateName# #_Full_Product_Name_# more text. text text #_Short_Description_#"
};
string pattern = "(?'string'#[^#]+#)";
foreach (string input in inputs)
{
MatchCollection matches = Regex.Matches(input, pattern);
Console.WriteLine(string.Join(",",matches.Cast<Match>().Select(x => x.Groups["string"].Value).ToArray()));
}
Console.ReadLine();
You regular expression is not correct. In addition, you want to loop through match if you want all matching.
static void Main(string[] args)
{
string input = "Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_#",
pattern = "#_[a-zA-Z_]*_#";
Match match = Regex.Match(input, pattern);
while (match.Success)
{
Console.WriteLine(match.Value);
match = match.NextMatch();
}
Console.ReadLine();
}
Result
Don't use anchors and change your regex to:
(#[^#]+#)
In regex the [^#] expression means any character BUT #
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = #"(#[^#]+#)";
Regex rgx = new Regex(pattern);
string sentence = "#blah blah# asdfasdfaf #somethingelse#";
foreach (Match match in rgx.Matches(sentence))
Console.WriteLine("Found '{0}' at position {1}",
match.Value, match.Index);
}
}
How to replace string between some Specific String in c#
For Exmaple
string temp = "I love ***apple***";
I need to get value between "***" string, i.e. "apple";
I have tried with IndexOf, but only get first index of selected value.
You should use regex for proper operation of various values like ***banana*** or ***nut*** so the code below may useful for your need. I created for both replacement and extraction of values between *** ***
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace RegexReplaceTest
{
class Program
{
static void Main(string[] args)
{
string temp = "I love ***apple***, and also I love ***banana***.";
//This is for replacing the values with specific value.
string result = Regex.Replace(temp, #"\*\*\*[a-z]*\*\*\*", "Replacement", RegexOptions.IgnoreCase);
Console.WriteLine("Replacement output:");
Console.WriteLine(result);
//This is for extracting the values
Regex matchValues = new Regex(#"\*\*\*([a-z]*)\*\*\*", RegexOptions.IgnoreCase);
MatchCollection matches = matchValues.Matches(temp);
List<string> matchResult = new List<string>();
foreach (Match match in matches)
{
matchResult.Add(match.Value);
}
Console.WriteLine("Values with *s:");
Console.WriteLine(string.Join(",", matchResult));
Console.WriteLine("Values without *s:");
Console.WriteLine(string.Join(",", matchResult.Select(x => x.Trim('*'))));
}
}
}
And a working example is here: http://ideone.com/FpKaMA
Hope this examples helps you with your issue.