Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have a string like this:
string str = "Property first {prop1=val1;prop2=val2}this is reg table[uvm]dsfhsjhsdj[/uvm]this is uvm test{pp1=vv2}";
And I need to get [uvm]...[/uvm] string.
I have tried this:
reg = new Regex(#"(\[uvm\].*?\[\\uvm\])");
string s = reg.Match(str).Groups[0].Value;
But it is not working. It does not match. What should I do?
The problem is not the Regular Expression, but rather the string input.
You input contains [/uvm] and not [\uvm] which of course won't be matched by the Regular Expression.
Also, I would suggest you to move the Capture to catch the inside of uvm, by simply moving the parenthesis inside the regex, like this:
\[uvm\](.*?)\[\\uvm\]
The regex you're using is a little off - you're using the wrong type of slash, try this:
var reg = new Regex(#"(\[uvm\].*?\[\/uvm\])");
Also note that if you want to retrieve the text within the [uvm] tags, you would need an additional group. Here's a working example:
var str = "Property first {prop1=val1;prop2=val2}this is reg table[uvm]dsfhsjhsdj[/uvm]this is uvm test{pp1=vv2}";
var reg = new Regex(#"(\[uvm\](.*?)\[\/uvm\])");
var m1 = reg.Match(str).Groups[1].Value; // = "[uvm]dsfhsjhsdj[/uvm]"
var m2 = reg.Match(str).Groups[2].Value; // = "dsfhsjhsdj"
Working example
The accessing of the groups would obviously need to be much more robust - this is purely for demonstrative purposes.
You do not need to set any capturing groups and get your value using Regex.Match(str).Value if you use look-arounds:
string str = "Property first {prop1=val1;prop2=val2}this is reg table[uvm]dsfhsjhsdj[/uvm]this is uvm test{pp1=vv2}";
Regex rx = new Regex(#"(?<=\[uvm]).*?(?=\[/uvm])");
foreach (Match m in rx.Matches(str))
{
Console.WriteLine(m.Value);
}
Or, you can get all matches using LINQ:
var matches = rx.Matches(str).Cast<Match>().Select(p => p.Value).ToList();
See IDEONE demo
REGEX EXPLANATION:
(?<=\[uvm]) - A positive look-behind making sure there is literal [uvm] string before our expected result
.*? - Any string of characters (except newline, if you need . to match a newline, add RegexOptions.Singleline flag in the Regex declaration) as few as possible (due to *? lazy quantifier)
(?=\[/uvm]) - A positive look-ahead that makes sure there is literal [/uvm] after our expected result.
See regex demo
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
In a string like
[\\\x2286400000\\\x22,\\\x22604800000\\\x22,2.0]\\n,null,1]\\n\x22,\x22mnr_crd\x22:\x221\x22,\x22msg_dsc\x22:\x22From your Internet address\x22,\x22msg_dvl\x22:\x22Reported by this computer\x22,\x22msg_err\x22:\x22Location unavailable\x22,\x22msg_gps\x22:\x22Using GPS\x22,\x22msg_unk\x22:\x22Unknown\x22,\x22msg_upd\x22:\x22Update location\x22,\x22msg_use\x22:\x22Use precise location\x22,\x22uul_text\x22:\x22Home Location\x22}
I am trying to match Home location with the regex like
(?<=:\\x22Use precise location\\x22,\\x22uul_text\\x22:\\x22)(.+?)(?=\\x22})
Here is the whole code:
string locationRegExpression = "(?<=:\\x22Use precise location\\x22,\\x22uul_text\\x22:\\x22)(.+?)(?=\\x22})";
Regex locationMmatch = new Regex(locationRegExpression, RegexOptions.Singleline);
MatchCollection locationCollection = Regex.Matches(locationHtmlContent,locationRegExpression);
// lblCurrentLocation.Text = "Location: " + locationCollection[0];
MessageBox.Show(locationCollection[0].ToString());
The above regex code is working fine with the below html code in online regex tester sites but if I use the same regex in C# win forms. Its giving 0 results. Any idea?
Whole text here.
It seems you want to match a single substring in a string containing literal \x22 substrings. You need to make sure you match a literal \ symbol, that is, you need to use two literal backslashes in your pattern. It is better done with a verbatim string literal (to avoid overescaping, use #"...") and it is enough to use a Regex.Match method:
string locationRegExpression = #"(?<=:\\x22Use precise location\\x22,\\x22uul_text\\x22:\\x22)(.+?)(?=\\x22})";
Regex locationMmatch = new Regex(locationRegExpression, RegexOptions.Singleline);
Match locationMatch = locationMmatch.Match(locationHtmlContent);
if (locationMatch.Success)
{
MessageBox.Show(locationMatch.Value);
}
Note that it might probably be "simpler" to use a capturing group here rather than a combination of lookbehind and lookahead:
#":\\x22Use precise location\\x22,\\x22uul_text\\x22:\\x22(.+?)\\x22}"
and then
MessageBox.Show(locationMatch.Groups[1].Value)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have the below string (which was originally XML):
<Message><ProcedureName>TestUpdate</ProcedureName><Parameters><![CDATA[N'Yes',N'No']]></Parameters><MessageType>A</MessageType></Message>
I have tried the below but the text 'No' is dynamic (it can be a different value):
message.Replace("No", "********");
I'm not sure whether I can do this using string.Replace, Regex or a mix of both?
You can use regex to get string between 2 tags before replacing:
string str = "<Message><ProcedureName>TestUpdate</ProcedureName><Parameters><![CDATA[N'Yes',N'No']]></Parameters><MessageType>A</MessageType></Message>";
Match match = Regex.Match(str, #"CDATA\[.*\]");
if (match.Success)
{
Console.WriteLine(str_out);//"CDATA[N'Yes', N'No']]"
}
Assuming by 'dynamic' you mean it could be anything, including 'No', here's my attempt:
var source = "<Message><ProcedureName>TestUpdate</ProcedureName><Parameters><![CDATA[N'Yes',N'No']]></Parameters><MessageType>A</MessageType></Message>";
var regexstr = #"(.*\[CDATA\[.*,N')(.*)('\]\].*)";
var regex = new Regex(regexstr);
var matches = regex.Match(source);
Console.WriteLine($"{matches.Groups[1].Value}****{matches.Groups[3].Value}");
//Console Output: <Message><ProcedureName>TestUpdate</ProcedureName><Parameters><![CDATA[N'Yes',N'****']]></Parameters><MessageType>A</MessageType></Message>
This could possibly be optimised further but that is dependent on your source. Hope it helps!
This is what I have settled on. It is not perfect but it satisfies my requirement.
Match match = Regex.Match(message, #"CDATA\[.*\]");
if (match.Success)
{
maskedMessage = message.Replace(match.Value, "********");
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have following text with me,
File <a class='ub link' data-menu-identifier='files' data-url-identifier='/files/detail/n0tlz'>Medical bills & LTA.xlsx</a> was attached to the case by {updatedby} on {updatedon}
What I need is, I need regex that will give me 'n0tlz' from the given text. Please take note that this is not static I need to extract from this pattern.
I have achieved at some level but not getting how to get required text;
I have : '/files/detail/n0tlz' where '/files/detail/{code}' is always there, I just want value of {code} in given sample {code} = n0tlz
// Extract The filecode
const string pattern = #"files\/detail\/(.*)'>";
// Instantiate the regular expression object.
var r = new Regex(pattern, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
var m = r.Match(fileUpdate.UpdateText);
here m has value : /files/detail/n0tlz'>
but I just wants 'n0tlz' I feels I am too close, just one last step is requires to obtain code value.
// Extract The filecode
const string pattern = #"files\/detail\/(.*)'>";
// Instantiate the regular expression object.
var r = new Regex(pattern, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
var m = r.Match(fileUpdate.UpdateText);
if (m.Success && m.Groups.Count == 2 )
{
m.Groups[1].Value; // This is the expected result
}
If data-url-identifier='/files/detail/n0tlz'> always contains a '> you could use that as a delimiter. making your existing
files\/detail\/ into files\/detail\/ '>
now to capture the specific value you can use a simple capture group
(.*) which will catch any character between zero and unlimited times.
Combining the 2 would lead to files\/detail\/(.*)'>.
Edit
But this m have : /files/detail/n0tlz'> I just want 'n0tlz' can i get it?
Well, yes. Or to be even more detailed, you already have it!
Instead of using a var try defining the type itself. In this case that would be a Match. Taking a look at the properties you will see that it contains a lot more then just the whole match.
Groups will contain your value
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
My code is comparing a Regex pattern to a string value, and in my opinion it looks like it is a match. However the result is always false. I'm not seeing where my error is. Here are some lines of code:
string pattern = #"d{2}\[a-zA-Z]{1,2}\d{6}";
Regex regex = new Regex(pattern);
bool match = regex.IsMatch(value.ToString());
match is always = false. value.ToString is = "11D123456" which seems to me should match 2 digits, followed by 1 or 2 letters, followed by 6 digits.
If anyone can explain why it is not a successful match, that would be greatly appreciated.
Change your pattern from
d{2}\[a-zA-Z]{1,2}\d{6}
To
\d{2}[a-zA-Z]{1,2}\d{6}
You were treating both [ and d as literal characters.
You need to change to this \d{2}[a-zA-Z]{1,2}\d{6}.
Your initial regex is interpreted as
You need to change to \d{2}[a-zA-Z]{1,2}\d{6} ,which can be interpreted as
PD: I strongly recommend that you use Expresso. It's a free tool that help you learning and testing regex.
http://www.ultrapico.com/expresso.htm
using the debugger you will see that this will return true
string pattern = #"\d{2}[a-zA-Z]{1,2}\d{6}";
Regex regex = new Regex(pattern);
bool match = regex.IsMatch(value.ToString());
this was incorrect d{2}[a-zA-Z]{1,2}\d{6}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string like this
ABCD$-$ToBeFetched1/$-$ToBeFetched2/$-EF$GH
How do I retrieve the string between $ and /$?
Expected string should be
ToBeFetched1
ToBeFetched2
Regex r = new Regex(Regex.Escape("-$") + "(.*?)" + Regex.Escape(#"/$"));
MatchCollection matches = r.Matches("ABCD$-$ToBeFetched1/$-$ToBeFetched2/$-EF$GH");
foreach (Match match in matches)
{
Console.WriteLine(match.Groups[1].Value);
}
Here this will work for sure.
Since you have "open" and "close" markers, the regex expression would obviously be built around this form:
[head-marker: $] [the content you are interested in: anything] [tail-marker: /$]
so, with addition of a parentheses to form a capturing group:
$(.*)$
However, two problems here: * expressions are greedy (and you dont want it to be, as you want all smallest matches possible) - so it has to be weakened, and also the $ is a special character in regex, so it has to be escaped:
\$(.*?)/\$
this forms almost-good expression. It will however falsely match agains such input:
aaaaa/$bbbbb/$ccccc -> bbbbb
because the "head-marker" can skip the slash and hit the first dollar sign what most probably you wouldn't want. Hence, some lookbehind would be useful here too:
(?!</)\$(.*?)/\$
The ?!<XXXX instructs to match only if XXXX does not precede the potential match.
See also MSDN: Regex syntax and operators
edit: actually Arie's suggestion is much simplier as it doesn't use capturing group. Note the small difference though: Arie's example explicitely fobids the data to contain a dollar sign, so ABCD$-$ToBeFe$tched1/$- will result in tched1 not ToBeFe$tched1. If you need the latter, just change the inner [^$] part. Think and pick what you actually need!
Using String Methods:
string s ="ABCD$-$ToBeFetched1/$-$ToBeFetched2/$-EF$GH";
var results = s.Split('-')
.Where(x=> x.StartsWith("$") && x.EndsWith("/$"))
.Select(y=> y.Substring(1,y.Length - 3));
//Console.WriteLine("string1: {0}, string2:{1}",results.ToArray());
(?<=\$)[^$]{1,}(?=/\$)
(?<=\$) - positive lookbehind: it ensurers your match starts right after $ ($ not included in the match)
[^$]{1,} - matches characters other than $; {1,} instead of * to ensure there will be no empty matches (for strings lilke "$/$")
(?=/\$) - positive lookahead: it ensures your match ends right before /$ (/$ not included in the match)