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)
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 8 years ago.
Improve this question
I'm using c#. I need a method that will take a string as input, search for the percent symbol in that string, then return the number directly in front of the percent symbol. for example "asdf sdfa asf 32% asdf" would return 32. "asdfl asfi asdf kd 34.5% adsfkjfg" would return 34.5. I know how to find the index of the percent symbol then loop backwards searching for a space, and return everything in the middle. I feel there is probably a more efficient way to do it.
var result = str.Split(' ')
.Where(s => s.Contains('%'))
.Select(s => s.Trim('%'));
Explanation
Split turns your input string into an IEnumerable<string>, Where selects only those strings that contain the searched character % and Select projects each of those elements, such that the new elements do not contain the character %
You can use a Regular Expression to achieve this using the following pattern:
(^|\s)\d+(.\d+)?(?=%)
And in the code:
var match =
System.Text.RegularExpressions.Regex.Match(input, #"(^|\s)\d+(.\d+)?(?=%)");
if (match.Success)
{
string value = match.Value;
}
And here's the pattern broken down into pieces:
(^|\s): Specifies that the rest of the pattern should look either at the beginning of the string or after a white-space. As a result, "Hello 3%" would be a match, but "Hello3%" won't be.
\d+: Matches one or more digits.
(.\d+)?: Specifies that if there is a ". ", there should be one or more decimal digits as well.
(?=%): Is a lookahead group used to match a "%" and return everything captured before it (i.e. the value).
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
Having codes in the following format [Alphanumeric][Letter][Alphanumeric][Alphanumeric] i.e A1AA
Now I also have a dictionary of all the 4 letter words I am trying to block i.e R2D2
What I am looking for is a regular expression to find the matches for each code and item in my dictionary but also 1 step further and to replace characters and letters which look alike i.e. i and 1, s and 5 and see if any matches happen there.
Anything like that out there
Let's say your dictionnary contains this codes:
R2D2
C3P0
X5ZZ
I would load the dictionnary and build on the fly a regex. The final regex would be:
(?-i)(R2D2|C3P0|X5ZZ)
Then apply this regex to each of your codes
If Regex.Matches(finalRegex) Then
// Evil code catched
Else
// Nice code found ...
End If
I'll give you a headstart
var matches = Regex.Matches(#"A1AA", #"([a-zA-Z0-9][a-zA-Z][a-zA-Z0-9][a-zA-Z0-9])");
foreach(Match match in matches)
{
Console.WriteLine(match.Groups[1].Value);
}
This part of the Regex code [a-zA-Z0-9] will capture any character which is alphanumeric.
You can then do a foreach loop on the matches against a dictionary of words.
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 would like to remove all appearances of the character / and \ in a string if it appears consecutively more than twice, using Regex. This means, if a string contains abc////////////////////////def, I would like to get all / removed. However, it should not remove "the / in http://.
Could someone please suggest?
You can use /{3,}, which will match 3 or more occurrences of the / character.
var result = Regex.Replace("abc///def", "/{3,}", "");
Update: to reply to your comment, the * character is a metacharacter in regex, which holds a special meaning, so you need to escape it. Try this: \*{3,}. If you want to combine both characters, you can use a character class: [/*]{3,}. A character class is denoted by the square brackets. Inside a character class you don't need to escape metacharacters, which is why I simply list * inside without escaping it as I did earlier.
Use negative look-behind assertion:
#"(?<!https?:)/{2,}|\\{2,}"
For example:
Regex pattern = new Regex(#"(?<!https?:)/{2,}|\\{2,}");
Console.WriteLine(pattern.Replace(#"http://example.com", ""));
Console.WriteLine(pattern.Replace(#"abc//////////def", ""));
Console.WriteLine(pattern.Replace(#"abc\\\\\\\\\\def", ""));
prints
http://example.com
abcdef
abcdef
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
Can you please help me to find a expression to accept these :
C1D3
A1Z5R7
H2L7V5X3
but does not accept these :
A1B2A2 //Because the A repeated 2 times
C4F5F3
C2C1
B1B2F6
I am tring to create a expression to use it in C#.Net
In this sort of problem back-references are you're friend.
so (.).*\1 will match a character followed by anything followed by whatever the first capture group matched
Assuming you have a bunch of Capital Letter/Number pairs...
/^(([A-Z])(?!.*\2)[0-9])+$/g
Breakdown...
/^ # Start regex, and pattern match
( # Start group 1
([A-Z]) # Capture any character from A-Z into group 2
(?!.*\2) # Do negative lookahead `(?!...)` to ensure there is no repeat of the captured group 2 (`\2`), after zero or more of anything (`.*`)
[0-9] # Capture a digit
)+ # End group 1
$/g # End regex, and pattern match, with global flag set
Alternatively, for all tokens to avoid repetition equally...
/^(([A-Z0-9])(?!.*\2))+$/g
You can do it without regex:
StringReader reader = new StringReader(str);
string line;
while((line = reader.ReadLine()) != null)
{
if (line.Distinct().Count() != line.Length)
return false;
}
return true;
You can use this negative lookahead based rgex to avoid matching duplicate containing strings:
/^(?:(.)(?!.*?\1))+$/
/^(?:(.)(?!.*?\1))+$/.test('A1B2D3'); // true
/^(?:(.)(?!.*?\1))+$/.test('A1B2A3'); // false
string pattern=#"\w+";
var uniqueCharWords=Regex.Matches(input,pattern)
.Cast<Match>()
.Where(x=>x.Value.Distinct()==x.Value.Length);
If you are looking for a perfect regex,this is it
string pattern=#"\b(?!\w*(\w)\w*\1\w*)\w+\b";