Equivalent of Substring as a RegularExpression - c#

Ok, I need a general regular expression that will give me the x characters from a string starting at position y like the string's substring function:
input_str.Substring(y,x)
But as a C# regular expression.
Example:
1234567890 Substring(5,3) 678
I know you are thinking why not just use the Substring function? The short answer is because this goes as a data for an existing function and in this context it would be inelegant to create a whole separate data parsing mechanism. We'd like to get this working without changing the code.
I feel like this is really obvious--but I'm pretty inexperienced with regular expressions. Thanks in advance for any help.

.{y}(.{x}).* should do it, I think, then just pull out the capture group.

Related

Retrieve array from string with regular expression in C#

I have following string:
"option1,option2->data1,data2,data3,..."
I'm learning C# and also regular expressions, so I thought I might have some fun with it, but I can't figure out how to get an array from this.
For example, I'd like to retrieve array of strings that looks like this one:
[option1,option2,data1,data2,data3,...]
Here's regular expression I wrote in regex tester (.+),(.+)->((.+),?), but I'm not sure if this will work. And also I don't know how to use regex functions in C# to achieve this. I guess I should use something from System.Text.RegularExpressions but I'm not really sure what.
Long story short:
I want to get array from string using regular expressions.
"option1,option2->data1,data2,..." -> [option1,option2,data1,data2,...]
Thanks!
I would avoid RegularExpressions for this. you can simply do this:
string[] myArray = inputString.Replace("->", ",").Split(',');
It seems like you need direction more than an answer.
http://www.RegexHero.com is a good place to test your regex against strings.
http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet is a cheat sheet/guide for c# regex
http://www.dotnetperls.com/regex-match here's a good place to start with regex in c#
You haven't posed anything that string.Split can't handle:
var split = given.Split(new [] {",", "->"}, StringSplitOptions.None);

Deal with '#' through regex

Quick question , I have been trying to match any word containing a '#' from a string list and remove it, but I don't know how to handle it . been playing around on http://regexhero.net/tester/ trying but to no avail.
Essentially if it comes across #ff or wha#s up i will just regex.replace them.
any ideas on the Regular expression to use?.
Thanks.
Don't use regex - just use string.replace - it's a lot faster.
I have a previous answer that covers some hashtag matching approaches.
In summary, if you are pulling statuses containing hashtags from Twitter, you no longer need to find them yourself. You can now specify the include_entities parameter to have Twitter automatically call out mentions, links, and hashtags (if the method you are calling, like statuses/show supports this parameter.
If you just need the regular expression to locate the hashtags and capture it's elements, Twitter provides it in an open source library that contains the following pattern.
(^|[^0-9A-Z&/]+)(#|\uFF03)([0-9A-Z_]*[A-Z_]+[a-z0-9_\\u00c0-\\u00d6\\u00d8-\\u00f6\\u00f8-\\u00ff]*)
More detail and additional links are provided in the original answer.
So you're trying to remove any words containing a #?
If so, give this a try...
\w*#\w*
And replace with nothing, like so...
http://regexhero.net/tester/?id=cda1e713-bdab-4aa2-b63d-a87e9b2c9bce
apple# orange ban#ana becomes orange
But if you're simply trying to remove all instances of #, then String.Replace is the better choice. myString = myString.Replace("#", "");

RegEx replace with calculations?

Is it possible somehow to do a RegEx-replace with a calculation in the result? (in VS2010)
Such as:
Grid\.Row\=\"{[0-9]+}\"
to
Grid.Row="eval(int(\1) + 1)"
You can use a MatchEvaluator do achieve this, like
String s = Regex.Replace("1239", #"\d", m => (Int32.Parse(m.ToString()) + 1).ToString());
Output: 23410
Edit:
I just noticed... if you mean "using the VS2010 find-replace feature" and not "using C#", then the answer is "no", i am afraid.
You could always use capturing to retrieve any values you need for your calculation and then perform a RegEx Replace with a new RegEx that's constructed from you're equation and any values you captured.
If the equation doesn't use anything from the input text, one RegEx would be sufficient. You'd simply construct it by concatenating the static portions together with the computed value(s).
Unfortunately, C# and .NET do not provide an eval method or equivalent. However, it is possible to either use a library for expression parsing (a quick google gave me this .NET Math Expression Parser) or write your own (which is actually pretty easy, check out the Shunting-yard Algorithm and Postfix Notation). Simply capture the group then output the group value to the library/method you have written.
Edit: I see now you want this for the VS2010 program. This is unachievable unless you write your own VS extension. You could always write a program to search and replace your code and feed the code into it, then replace it the original code with its output.

Regular expression to define format of backup filenames

In the application I am currently working on, I have an option to create automatic backups of a certain file on the hard disk. What I would like to do is offer the user the possibility to configure the name of the file and its extension.
For example, the backup filename could be something like : "backup_month_year_username.bak". I had the idea to save the format in the form of a regular expression. For the example above, the regexp would look like :
"^backup_(?<Month>\d{2})_(?<Year>\d{2})_(?<Username>\w).(?<extension>bak)$"
I thought about using regex because I will also have to browse through the directory of backuped files to delete those older than a certain date. The main trouble I have now is how to create a filename using the regex. In a way I should replace the tags with the information. I could do that using regex.replace and another regex, but I feel it's a big weird doing that and it might be a better way.
Thanks
[Edit] Maybe I wasn't really clear in the first go, but the idea is of course that the user (in this case an admin that will know regex syntax) will have the possibility to modify the form of the filename, that's all the idea behind it[/Edit]
... and if the regex changes, it is next to impossible to reconstruct a string from a given regex.
Edit:
Create some predefined "place-holders": %u could be the user's name, %y could be the year, etc.:
backup_%m_%y_%u.bak
and then simple replace the %? with their actual values.
It sounds like you're trying to use the regular expression to create the file name from a pattern which the user should be able to specify.
Regular expressions can - AFAIK - not be used to create output, but only to validate input, so you'd have the user specify two things:
a file name production pattern like Bart suggested
a validation pattern in form of a regular expression that helps you split the file names into their parts
EDIT
By the way, your sample regex contains an error: The "." is use for "any character", also \w only matches one word character, so I guess you meant to write
"^backup_(?<Month>\d{2})_(?<Year>\d{2})_(?<Username>\w+)\.(?<extension>bak)$"
If the filename is always in this form, there is no reason for a regex, as it's easier to process with string.Split ...
With Bart's solution it is easy enough to split (using string.Split) the generated file name using underscore as the delimiter, to get back the information.
Ok, I think I have found a way to use only the regex. As I am using groups to get the information, I will use another regular expression to match the regular expression and replace the groups with the value:
Regex rgx = new Regex("\(\?\<Month\>.+?\)");
rgx.Replace("^backup_(?<Month>\d{2})_(?<Year>\d{2})_(?<Username>\w+)\.(?<extension>bak)$"
, DateTime.Now.Month.ToString());
Ok, it's really a hack, but at least it works and I have only one pattern defined by the user. It might not work if the regex is too complex, but I think I can deal with that problem.
What do you think?

Parser using RegEx and XML, in C#

I am making an application where I need to verify the syntax of each line which contains a command involving a keyword as the first word.
Also, if the syntax is correct I need to check the type of the variables used in the keywords.
Like if there's a print command:
print "string" < variable < "some another string" //some comments
print\s".*"((\s?<\s?".*")*\s?<\s?(?'string1'\w+))?(\s*//.*)?
So i made the following Regex:
\s*[<>]\s*((?'variant'\w+)(\[\d+\])*)
This is to access all words in variant group to extract the variables used and verify their type.
Like this my tool has many keywords and currently I am crudely writing regex for each keyword. And if there's a change tomorrow I would be replacing the respective change everytime everywhere in every keyword.
I am storing a Regex for each keyword in an XML file. However I was interested in making it extensible, where say the specification changes tomorrow so I need to change it only once and it would reflect in all the places something like I transform the print regex to:
print %string% (%<% %string%|%variable%)* %comments%
Now like this, I write a specification for each keyword and write the definition of string, variable, comments in another file which stores their regex. Then I write a parser which parses this string and create a regex string for me.
Is this possible?
Is there any better way of doing this or is there any way I can do this in XML?
Last time I asked a question like this, someone pointed me to http://www.antlr.org/. Enjoy. :-)
I got an idea and made my own replacer. I used %myname% kind of tags to define my regular expression, and i wrote the definition of %myname% tags seperately using regex. Then i scanned the string recursively and converted the occurance of %myname% tags to the specification they had. It did my work.Thanks any ways

Categories