I have such types of file paths:
\\server\folder\folder1\folder3\someFile.txt,
\\otherServer\folder123\folder1\folder3\someFile.txt
\\serv\fold\folder3\folder4\someFile.txt
I need to remove the first two segments of this path to make them as follows:
folder1\folder3\someFile.txt,
folder1\folder3\someFile.txt
folder3\folder4\someFile.txt
I'm doing it with c# and Regex.Replace but need a pattern.
Thanks.
It seems, that you work files' paths, and that's why I suggest using Path not Regex:
using System.IO;
...
string source = #"\\serv\fold\folder3\folder4\someFile.txt";
var result = Path.IsPathRooted(source)
? source.Substring(Path.GetPathRoot(source).Length + 1)
: source;
If you insist on regular expressions then
string result = Regex.Replace(source, #"^\\\\[^\\]+\\[^\\]+\\", "");
You can use the following regular expression pattern to remove the first two segments:
^\\[^\\]+\\[^\\]+\\
you can use Regex.Replace in C#
example:
string input = "\\\\server\\folder\\folder1\\folder3\\filename.txt";
string pattern = "^\\\\[^\\\\]+\\\\[^\\\\]+\\\\";
string replacement = "";
var result = Regex.Replace(input, pattern, replacement);
output:
folder1\folder3\filename.txt
Related
I need to extract from the below string
2_240219_0.vnd as 240219
I have tried as follows: _[0-9]+_
This gives me _240219_
How do I remove the _ from both ends.
I would actually recommend not even using regex in this case. A simple string split on underscore should do just fine:
string input = "2_240219_0.vnd";
string middle = input.Split('_')[1];
Console.WriteLine(middle);
240219
You can try using a other regex: ([\d]{6,})
Match m = Regex.Match(2_240219_0.vnd, `([\d]{6,})`, RegexOptions.IgnoreCase);
I have a large file that references a URL within it. It always has the format:
URL="........." - where the ellipses are the URL.
I have a new URL would like to replace the previous with and I was wondering if there was any sort of wildcard string replace.
Example:
A large string contains: URL="google.com"
Problem:
I need to replace the above with: URL="123.com"
Thanks for any help
Try this:
string largeString = ".....URL=\"google.com\" ....";
string pattern = "URL=\"([^ \"]*)\"";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(largeString, "URL=\"123.com\"");
Regex.Replace(line, #"URL\s*=\s*"".+?""", #"URL=""123.com""");
For example, my regular expression found the string: some\file\path.xml and I want it to be changed to new_root\some\file\path.xml. Is there a way to do this using the regex replace method? If not, what is the preferred way to do this?
It appears that you can do what you are asking using Regex.Replace.
Check out Substitutions in Regular Expressions article on MSDN.
Example:
var path = #"C:\some\file\path.xml";
var result = Regex.Replace(path, #"(C:\\)(.*)", "$1new_root\\$2");
Result is C:\new_root\some\file\path.xml.
You don't need regex for that, just find the string you want with a buid-in function and concatenate with what you want.
For a more general search/replace you can do this:
string pattern = #"(?>\w+\\)+\w+.xml";
string replacement = "new_root\\$0";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
I need to remove certain strings after another string within a piece of text.
I have a text file with some URLs and after the URL there is the RESULT of an operation. I need to remove the RESULT of the operation and leave only the URL.
Example of text:
http://website1.com/something Result: OK(registering only mode is on)
http://website2.com/something Result: Problems registered 100% (SOMETHING ELSE) Other Strings;
http://website3.com/something Result: error: "Âíèìàíèå, îáíàðóæåíà îøèáêà - Ìåñòî æèòåëüñòâà ñîäåðæèò íåäîïóñòèìûå ê
I need to remove all strings starting from Result: so the remaining strings have to be:
http://website1.com/something
http://website2.com/something
http://website3.com/something
Without Result: ........
The results are generated randomly so I don't know exactly what there is after RESULT:
One option is to use regular expressions as per some other answers. Another is just IndexOf followed by Substring:
int resultIndex = text.IndexOf("Result:");
if (resultIndex != -1)
{
text = text.Substring(0, resultIndex);
}
Personally I tend to find that if I can get away with just a couple of very simple and easy to understand string operations, I find that easier to get right than using regex. Once you start going into real patterns (at least 3 of these, then one of those) then regexes become a lot more useful, of course.
string input = "Action2 Result: Problems registered 100% (SOMETHING ELSE) Other Strings; ";
string pattern = "^(Action[0-9]*) (.*)$";
string replacement = "$1";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
You use $1 to keep the match ActionXX.
Use Regex for this.
Example:
var r = new System.Text.RegularExpressions.Regex("Result:(.)*");
var result = r.Replace("Action Result:1231231", "");
Then you will have "Action" in the result.
You can try with this code - by using string.Replace
var pattern = "Result:";
var lineContainYourValue = "jdfhkjsdfhsdf Result:ljksdfljh"; //I want replace test
lineContainYourValue.Replace(pattern,"");
Something along the lines of this perhaps?
string line;
using ( var reader = new StreamReader ( File.Open ( #"C:\temp\test.txt", FileMode.Open ) ) )
using ( var sw = new StreamWriter(File.Open( #"C:\Temp\test.edited.txt", FileMode.CreateNew ) ))
while ( (line = reader.ReadLine()) != null )
if(!line.StartsWith("Result:")) sw.WriteLine(line);
You can use RegEx for this kind of processing.
using System.Text.RegularExpressions;
private string ParseString(string originalString)
{
string pattern = ".*(?=Result:.*)";
Match match = Regex.Match(originalString, pattern);
return match.Value;
}
A Linq approach:
IEnumerable<String> result = System.IO.File
.ReadLines(path)
.Where(l => l.StartsWith("Action") && l.Contains("Result"))
.Select(l => l.Substring(0, l.IndexOf("Result")));
Given your current example, where you want only the website, regex match the spaces.
var fileLine = "http://example.com/sub/ random text";
Regex regexPattern = new Regex("(.*?)\\s");
var websiteMatch = regexPattern.Match(fileLine).Groups[1].ToString();
Debug.Print("!" + websiteMatch + "!");
Repeating for each line in your text file. Regex explained: .* matches anything, ? makes the match ungreedy, (brackets) puts the match into a group, \\s matches whitespace.
I'm trying to create a new file path in regex, in order to move some files. Say I have the path:
c:\Users\User\Documents\document.txt
And I want to convert it to:
c:\Users\User\document.txt
Is there an easy way to do this in regex?
If all you need is to remove the last folder name from the file path then I think it would be easier to use built-in FileInfo, DirectoryInfo and Path.Combine instead of regular expressions here:
var fileInfo = new FileInfo(#"c:\Users\User\Documents\document.txt");
if (fileInfo.Directory.Parent != null)
{
// this will give you "c:\Users\User\document.txt"
var newPath = Path.Combine(fileInfo.Directory.Parent.FullName, fileInfo.Name);
}
else
{
// there is no parent folder
}
One way in Perl regex flavour. It removes last directory in the path:
s/[^\\]+\\([^\\]*)$/$1/
Explanation:
s/.../.../ # Substitute command.
[^\\]+ # Any chars until '\'
\\ # A back-slash.
([^\\]*) # Any chars until '\'
$ # End-of-line (zero-width)
$1 # Substitute all characters matched in previous expression with expression between parentheses.
You can give this a try although it is a Java Code
String original_path = "c:\\Users\\User\\Documents\\document.txt";
String temp_path = original_path.substring(0,original_path.lastIndexOf("\\"));
String temp_path_1 = temp_path.substring(0,temp_path.lastIndexOf("\\"));
String temp_path_2 = original_path.substring(original_path.lastIndexOf("\\")+1,original_path.length());
System.out.println(temp_path_1 +"\\" + temp_path_2);
You mentioned that transformation is the same every time so, it is not always a good practice to rely on regexp for things which can be done using String manipulations.
Why not some combination of pathStr.Split('\\'), Take(length - 2), and String.Join?
Use Regex replace method. Find what you are looking for, then replace it with nothing (string.empty) here is the C# code:
string directory = #"c:\Users\User\Documents\document.txt";
string pattern = #"(Documents\\)";
Console.WriteLine( Regex.Replace(directory, pattern, string.Empty ) );
// Outputs
// c:\Users\User\document.txt