I'd like to provide users with a fancy license key textbox, that would insert the dashes.
The key is supposed to be 20 characters long ( 4 groups of 5 characters )
I tried using regex, first:
Regex.Replace( text, ".{5}", "$0-" );
that is a problem as the dash is inserted even when there's no following characters, e.g
AAAAA-, that results in not being able to remove the dash as it's automatically re-inserted.
then I thought about telling the regex there should be a following character
Regex.Replace( text, "(.{5})(.)", "$1-$2" );
but that splits the key into group of 5-6-6...
Any ideas?
Use a negative lookahead to avoid - to be added at the last. It matches each 5 digits of input string from the first but not the last 5 digits.
.{5}(?!$)
Replacement string
$0-
DEMO
string str = "12345678909876543212";
string result = Regex.Replace(str, #".{5}(?!$)", "$0-");
Console.WriteLine(result);
Console.ReadLine();
Output:
12345-67890-98765-43212
IDEONE
.{5}[^$]
Use this.This will not put a - at the end.
Replace by
$0-
See demo.
http://regex101.com/r/vY0rD6/3
A linq style method might be to your liking if you fancy a non-regex way...
This can be ran in LinqPad:
var sourceReg = "abcdeFGHIJ12345klmno";
var splitLength=5;
var regList = Enumerable.Range(0, sourceReg.Length/splitLength).Select(i => sourceReg.Substring(i*splitLength, splitLength));
regList.Dump("Registration List");
var regSeparated = string.Join("-", regList);
regSeparated.Dump("Registration with Separators");
Note: doesn't take into account reg codes that don't divide exactly.
See the method above plus others in a similar question:
Add separator to string at every N characters?
Code
string key = "12345678909876543212";
licenseBox.Text = System.Text.RegularExpressions.Regex.Replace(key, #".{5}(?!$)", "$0-");
"As Mentioned Above" - Should work fine.
And the following might also work for you.
Code
string key = "12345678909876543212";
licenseBox.Text = String.Format("{0}-{1}-{2}-{3}", key.Substring(0, 5), key.Substring(5, 5), key.Substring(10, 5), key.Substring(15, 5));
Output
12345-67890-98765-43212
Related
I have a string and I want to get the words after the last dot in the string.
Example:
input string = "XimEngine.DynamicGui.PickKind.DropDown";
Result:
DropDown
There's no need in Regex, let's find out the last . and get Substring:
string result = input.Substring(input.LastIndexOf('.') + 1);
If input doesn't have . the entire input will be returned
Not a RegEx answer, but you could do:
var result = input.Split('.').Last();
In Regex you can tell the parser to work from the end of the string/buffer by specifying the option RightToLeft.
By using that we can just specify a forward pattern to find a period (\.) and then capture (using ( )) our text we are interested into group 1 ((\w+)).
var str = "XimEngine.DynamicGui.PickKind.DropDown";
Console.WriteLine(Regex.Match(str,
#"\.(\w+)",
RegexOptions.RightToLeft).Groups[1].Value);
Outputs to console:
DropDown
By working from the other end of the string means we don't have to deal with anything at the beginning of the string to where we need to extract text.
This is probably a super easy question but I can't seem to figure it out. Do you know how to extract just the portion after the '/' in a string. So for like the following:
[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]
So I just want the 'OrderConfirmation_SynergyWorldInc' portion. I got 271 entries where I gotta extract just the end portion (the all have the portions before that in all of them, if that helps).
Thanks!!
IF YOU HAVE A SINGLE ENTRY...
You need to use LastIndexOf with Substring after a bit of trimming:
var s = #"[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]";
s = s.Trim('[',']');
Console.Write(s.Substring(s.LastIndexOf('\\') + 1));
Result: OrderConfirmation_SynergyWorldInc
IF YOU HAVE MULTIPLE RECORDS...
You can use a regex to extract multiple matches from a large text containing [...] substring:
[^\\\[\]]+(?=\])
See demo
For [HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc][SOMEENTRY] string, you will then get 2 results:
The regex matches
[^\\\[\]]+ - 1 or more characters other than ], [ and \
(?=\]) - before the end ] character.
C#:
var results = Regex.Matches(s, #"[^\\\[\]]+(?=\])").OfType<Match>().Select(p => p.Value).ToList();
var s = #"[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]";
Console.WriteLine (s.Trim(']').Split('\\').Last());
prints
OrderConfirmation_SynergyWorldInc
var key = #"[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]";
key = key.Replace("[", string.Empty);
key = key.Replace("]", string.Empty);
var splitkeys =key.Split('\\');
if (splitkeys.Any())
{
string result = splitkeys.Last();
}
Try:
string orderConfirmation = yourString.Split(new []{'\\\'}).Last();
You may also want to remove the last character if the brackets are included in the string.
string pattern = ".*\\(\w*)";
string value = "[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]"
Regex r = new Regex(pattern);
Match m = r.Match(value);
I'm searching for a regular expression that will extract 0263563
from
;010263563=2119?
and 0267829
from
%00000026782904?;010267829=4119?
(Must be the same regular expression).
Start at the 3rd character after the semicolon and take 7 characters.
;..(\d{7})
or more general:
;..(.{7})
Or according to comment : "To clarify characters to take are digits"
;\d\d(\d{7})
Well, you need this:
;\d{2}(\d+)
The First group will contain the number you want.
;[\S]{2}([\S]{7})
Since you said characters and not numbers, but it would work either way
For rules that are that precise (start 3 chars after ;, then next 7), you could use a plain substring:
string s = "%00000026782904?;010267829=4119?";
var pos = s.IndexOf(';');
var number = s.Substring(pos+3, 7);
And of course, test whether that IndexOf really found the ;
The below regex would exactly 7 digits which must be preceded by a ; , any two characters.
(?<=;.{2})\d{7}
Code:
String input = #";010263563=2119?
%00000026782904?;010267829=4119?";
Regex rgx = new Regex(#"(?<=;.{2})\d{7}");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[0].Value);
IDEONE
Output:
0263563
0267829
Assuming regex is not an absolute requirement, you could use:
var input = "%00000026782904?;010267829=4119?";
// output will be: 0267829
var digits = input.SkipWhile(x => x != ';').Skip(3).Take(7).ToArray();
var output = new string(digits);
Suppose I have a string
Likes (20)
I want to fetch the sub-string enclosed in round brackets (in above case its 20) from this string. This sub-string can change dynamically at runtime. It might be any other number from 0 to infinity. To achieve this my idea is to use a for loop that traverses the whole string and then when a ( is present, it starts adding the characters to another character array and when ) is encountered, it stops adding the characters and returns the array. But I think this might have poor performance. I know very little about regular expressions, so is there a regular expression solution available or any function that can do that in an efficient way?
If you don't fancy using regex you could use Split:
string foo = "Likes (20)";
string[] arr = foo.Split(new char[]{ '(', ')' }, StringSplitOptions.None);
string count = arr[1];
Count = 20
This will work fine regardless of the number in the brackets ()
e.g:
Likes (242535345)
Will give:
242535345
Works also with pure string methods:
string result = "Likes (20)";
int index = result.IndexOf('(');
if (index >= 0)
{
result = result.Substring(index + 1); // take part behind (
index = result.IndexOf(')');
if (index >= 0)
result = result.Remove(index); // remove part from )
}
Demo
For a strict matching, you can do:
Regex reg = new Regex(#"^Likes\((\d+)\)$");
Match m = reg.Match(yourstring);
this way you'll have all you need in m.Groups[1].Value.
As suggested from I4V, assuming you have only that sequence of digits in the whole string, as in your example, you can use the simpler version:
var res = Regex.Match(str,#"\d+")
and in this canse, you can get the value you are looking for with res.Value
EDIT
In case the value enclosed in brackets is not just numbers, you can just change the \d with something like [\w\d\s] if you want to allow in there alphabetic characters, digits and spaces.
Even with Linq:
var s = "Likes (20)";
var s1 = new string(s.SkipWhile(x => x != '(').Skip(1).TakeWhile(x => x != ')').ToArray());
const string likes = "Likes (20)";
int likesCount = int.Parse(likes.Substring(likes.IndexOf('(') + 1, (likes.Length - likes.IndexOf(')') + 1 )));
Matching when the part in paranthesis is supposed to be a number;
string inputstring="Likes (20)"
Regex reg=new Regex(#"\((\d+)\)")
string num= reg.Match(inputstring).Groups[1].Value
Explanation:
By definition regexp matches a substring, so unless you indicate otherwise the string you are looking for can occur at any place in your string.
\d stand for digits. It will match any single digit.
We want it to potentially be repeated several times, and we want at least one. The + sign is regexp for previous symbol or group repeated 1 or more times.
So \d+ will match one or more digits. It will match 20.
To insure that we get the number that is in paranteses we say that it should be between ( and ). These are special characters in regexp so we need to escape them.
(\d+) would match (20), and we are almost there.
Since we want the part inside the parantheses, and not including the parantheses we tell regexp that the digits part is a single group.
We do that by using parantheses in our regexp. ((\d+)) will still match (20), but now it will note that 20 is a subgroup of this match and we can fetch it by Match.Groups[].
For any string in parantheses things gets a little bit harder.
Regex reg=new Regex(#"\((.+)\)")
Would work for many strings. (the dot matches any character) But if the input is something like "This is an example(parantesis1)(parantesis2)", you would match (parantesis1)(parantesis2) with parantesis1)(parantesis2 as the captured subgroup. This is unlikely to be what you are after.
The solution can be to do the matching for "any character exept a closing paranthesis"
Regex reg=new Regex(#"\(([^\(]+)\)")
This will find (parantesis1) as the first match, with parantesis1 as .Groups[1].
It will still fail for nested paranthesis, but since regular expressions are not the correct tool for nested paranthesis I feel that this case is a bit out of scope.
If you know that the string always starts with "Likes " before the group then Saves solution is better.
I have a text file for processing, which has some numbers. I want JUST text in it, and nothing else. I managed to remove the punctuation marks, but how do I remove the numbers? I want this using C# code.
Also, I want to remove words with length greater than 10. How do I do that using Reg Expressions?
You can do this with a regex:
string withNumbers = // string with numbers
string withoutNumbers = Regex.Replace(withNumbers, "[0-9]", "");
Use this regex to remove words with more than 10 characters:
[\w]{10, 100}
100 defines the max length to match. I don't know if there is a quantifier for min length...
Only letters and nothing else (because I see you also want to remove the punctuation marks)
Regex.IsMatch(input, #"^[a-zA-Z]+$");
You can also use string.Join:
string s = "asdasdad34534t3sdf43534";
s = string.Join(null, System.Text.RegularExpressions.Regex.Split(s, "[\\d]"));
The Regex.Replace method should do the trick.
// regex to match any digit
var regex = new Regex("\d");
// replace all matches in input with empty string
var output = regex.Replace(input, String.Empty);