Regex expression -string between first and last single quotes [duplicate] - c#

This question already has answers here:
C# Regular Expressions, string between single quotes
(4 answers)
Closed 5 years ago.
I have some strings. I want total string between first and last single quote
for example:
string val = "'Scale['#13212']'"; //--->Scale['#13212']
string val2= "'Scale[#13212']"; //--->Scale[#13212
string val3="abc'23'asad"; //--->23
I have use the following regex-#".*'(.*?)'.*" but it only displays string between last two.
for example:
string val = "'Scale['#13212']'"; //--->]
It is working fine with greedy when I use to capture the whole value of a string and a group(in group[1] ONLY) enclose with a pair of single quote
But when I want to capture the whole value of a string and a group(in group[1] ONLY) enclose with multiple pair of single quote , it only capture the value of string enclose with last pair but not the string between first and last single quotes.
for example:
string val1 = "Content:abc'23'asad"; //--->23
string val2 = "Content:'Scale['#13212']'ta";
Match match1 = Regex.Match(val1, #".*'(.*)'.*");
Match match2 = Regex.Match(val2, #".*'(.*)'.*");
if (match1.Success)
{
string value1 = match1.Value;
string GroupValue1 = match1.Groups[1].Value;
Console.WriteLine(value1);
Console.WriteLine(GroupValue1);
string value2 = match2.Value;
string GroupValue2 = match2.Groups[1].Value;
Console.WriteLine(value2);
Console.WriteLine(GroupValue2);
Console.ReadLine();
// using greedy For val1 i am getting perfect value for-
// value1--->Content:abc'23'asad
// GroupValue1--->23
// BUT using greedy For val2 i am getting the string elcosed by last single quote-
// value2--->Content:'Scale['#13212']'ta
// GroupValue2---> ]
// But i want GroupValue2--->Scale['#13212']
}
Please help!

Just use greedy .* between quotes:
'(.*)'
Demo

You can use Positive Lookbehind and Positive Lookahead to take the text between the quotes (Demo)
(?<=\').*(?=\')

Try below
string test= "'$get this$' test value";
string getvalue = Regex.Match(test, #"\'(.*?)\'").Groups[1].ToString();

Related

Performing OR in regex capture groups [duplicate]

This question already has answers here:
Using alternation and grouping constructs
(2 answers)
Closed 4 years ago.
I would like a match if the value contains either digits or matches the pattern [lookup('key')] where key can be any string.
Using either pattern on its own works. For example this works.
string value = "[lookup('anykey')]";
if (!Regex.IsMatch(value, "^\\[(lookup)\\(.*\\)\\]$"))
{
Console.WriteLine("no match");
}
I couldn't get both to work with a single regex.
if (!Regex.IsMatch(value, "((\\d+) | (\\[(parameter)\\(.*\\)\\]))"))
{
Console.WriteLine("no match");
}
Any idea?
In your regex you should remove spaces, try:
\d+|\[lookup\('[^']+'\)\]
First of all whenever I use regular expression in c# or for that matter any string that has characters that require escaping I prefix the string with '#' symbol, which saves me from using double escapes:)...I find it easier
Ok now to the answer, here is what I think you are looking for
static void Main(string[] args)
{
//string value = "[lookup('BlahBlah')]";
string value = "789897";
Match m = Regex.Match(value, #"((\d+)|(\[lookup\(\'([^\']+)\'\)\]))") ;
if (m.Success)
{
string num = m.Groups[2].Value;
string key = m.Groups[4].Value;
}
}
Notice how the string was prefixed with the '#' symbol and I didn't have to use double escapes for symbol \.
Since we are using so many parenthesis, we have 5 groups overall and if you want the number then you take the value of group 1, if you want the key the you take the value of group 4. If the 'num' is an empty string that means no number was supplied etc...
Hope that helps .....

Modifying string value

I have a string which is
string a = #"\server\MainDirectory\SubDirectoryA\SubDirectoryB\SubdirectoryC\MyFile.pdf";
The SubDirectoryB will always start with a prefix of RN followed by 6 unique numbers. Now I'm trying to modify SubDirectoryB parth of the string to be replaced by a new value lets say RN012345
So the new string should look like
string b = #"\server\MainDirectory\SubDirectoryA\RN012345\SubdirectoryC\MyFile.pdf";
To achieve this I'm making use of the following helper method
public static string ReplaceAt(this string path, int index, int length, string replace)
{
return path.Remove(index, Math.Min(length, path.Length - index)).Insert(index, replace);
}
Which works great for now.
However the orginial path will be changing in the near future so it will something like #\MainDirectory\RN012345\AnotherDirectory\MyFile.pdf. So I was wondering if there is like a regex or another feature I can use to just change the value in the path rather than providing the index which will change in the future.
Assuming you need to only replace those \RNxxxxxx\ where each x is a unique digit, you need to capture the 6 digits and analyze the substring inside a match evaluator.
var a = #"\server\MainDirectory\SubDirectoryA\RN012345\SubdirectoryC\MyFile.pdf";
var res = Regex.Replace(a, #"\\RN([0-9]{6})\\", m =>
m.Groups[1].Value.Distinct().Count() == m.Groups[1].Value.Length ?
"\\RN0123456\\" : m.Value);
// res => \server\MainDirectory\SubDirectoryA\RN0123456\SubdirectoryC\MyFile.pdf
See the C# demo
The regex is
\\RN([0-9]{6})\\
It matches a \ with \\, then matches RN, then matches and captures into Group 1 six digits (with ([0-9]{6})) and then will match a \. In the replacment part, the m.Groups[1].Value.Distinct().Count() == m.Groups[1].Value.Length checks if the number of distinct digits is the same as the number of the substring captured, and if yes, the digits are unique and the replacement occurs, else, the whole match is put back into the replacement result.
Use String.Replace
string oldSubdirectoryB = "RN012345";
string newSubdirectoryB = "RN147258";
string fileNameWithPath = #"\server\MainDirectory\SubDirectoryA\RN012345\SubdirectoryC\MyFile.pdf";
fileNameWithPath = fileNameWithPath.Replace(oldSubdirectoryB, newSubdirectoryB);
You can use Regex.Replace to replace the SubDirectoryB with your required value
string a = #"\server\MainDirectory\SubDirectoryA\RN123456\SubdirectoryC\MyFile.pdf";
a = Regex.Replace(a, "RN[0-9]{6,6}","Mairaj");
Here i have replaced a string with RN followed by 6 numbers with Mairaj.

splitting the string and choosing the middle part containing two set of parenthesis [duplicate]

This question already has answers here:
How do I extract text that lies between parentheses (round brackets)?
(19 answers)
Closed 7 years ago.
As I know for selecting a part of a string we use split. For example, if node1.Text is test (delete) if we choose delete
string b1 = node1.Text.Split('(')[0];
then that means we have chosen test, But if I want to choose delete from node1.Text how can I do?
Update:
Another question is that when there are two sets of parenthesis in the string, how one could aim at delete?. For example is string is test(2) (delete) - if we choose delete
You can also use regex, and then just remove the parentheses:
resultString = Regex.Match(yourString, #"\((.*?)\)").Value.
Replace("(", "").Replace(")", "");
Or better:
Regex.Match(yourString, #"\((.*?)\)").Groups[1].Value;
If you want to extract multiple strings in parentheses:
List<string> matches = new List<string>();
var result = Regex.Matches(yourString, #"\((.*?)\)");
foreach(Match x in result)
matches.Add(x.Groups[1].Value.ToString());
If your string is always xxx(yyy)zzz format, you can add ) character so split it and get the second item like;
var s = "test (delete) if we choose delete";
string b1 = s.Split(new[] { '(', ')' })[1];
string tmp = node1.Text.Split('(')[1];
string final = tmp.Split(')')[0];
Is also possible.
With the index [x] you target the part of the string before and after the character you have split the original string at. If the character occurs multiple times, your resulting string hat more parts.

Why does my regular expression pattern in C# return an empty string?

I have a a string that's formatted such \\\State\city".
I want to return only the State portion and then only the city portion into respective variables.
I tried using a pattern of ^\\\\[a-zA-Z]\ to return the state portion and then a pattern of ^\\[a-zA-Z] for the city portion. The results are always an empty string.
state = Regex.Match("\\\Washington\\Seattle","^\\\\[a-zA-Z]\"].ToString();
Backslash serves as an escape character. For every single (\) backslash you need two backslashes (\\).
Also you do not need the beginning of line anchor ^ on your second regular expression example because that part is obviously not at the beginning of the string. Below is an example of how you could do this.
String s = #"\\Washington\Seattle";
Match m = Regex.Match(s, #"(?i)^\\\\([a-z]+)\\([a-z]+)");
if (m.Success) {
String state = m.Groups[1].Value;
String city = m.Groups[2].Value;
Console.WriteLine("{0}, {1}", city, state); // => "Seattle, Washington"
}
Try this non-RegEx answer:
string data = #"\\Washington\Seattle";
string state = data.Trim('\\').Split('\\')[0];
string city = data.Trim('\\').Split('\\')[1];
Console.WriteLine("{0}, {1}", city, state);
This is trimming the double backslashes, then splitting at the first backslash.
Consider the following code to match State and City...
var state = Regex.Match(#"\\Washington\Seattle", #"(?<=\\\\).*(?=\\)");
var city = Regex.Match(#"\\Washington\Seattle", #"(?<=\\\\.*?\\).*");
You need to escape backslashes in regex. So anywhere that you would have a single \, instead have \\
Also [a-zA-Z] will only match once. Use a + to match once or more
So that would make your state regex:
^\\\\[a-zA-Z]+\\
Additionally, backslashes in strings in C# also need to be escaped. So either double up again, or use the # character:
state = Regex.Match(#"\\Washington\Seattle",#"^\\\\[a-zA-Z]+\\").ToString();
You only allow one character to stand between your backslashes. what you actually want is [a-zA-Z]* with the asterisk.

Regex 11 digit string capturing

String pattern = #"^(\d{11})$";
String input = "You number is:11126564312 and 12234322121 \n\n23211212345";
Match match = Regex.Match(input,pattern);
From the above code I am planning to capture the 11 digit strings present in above text but match.Success is always returning false. Any ideas.
This is because you have used ^ and $.
Explaination: The meaning of your regular expression is "match any string that contains exactly 11 digits from start to end". The string You number is:11126564312 and 12234322121 \n\n23211212345 is not a string like that. 01234567890 is like that string.
What you need: You need regular expression for match any string that contains exactly 11 digits. start to end is omitted. ^ and $ is used for this. So you need this regex.
String pattern = #"(\d{11})";
As the sub-pattern to capture contains the whole regex you dont need () at all. Just the regex ill do.
String pattern = #"\d{11}";
String pattern = #"^(\d{11})$";
String input = "11126564312"
Match match = Regex.Match(input,pattern);
will pass.
Your Regex specify it has to be 11 numbers ONLY
^ = starts with
$ = ends with
if you want to check if it contains 11 numbers change the regex to
String pattern = #"\d{11}";
Your Regex matches a string that has exactly 11 digits, but no text before, between or after. That is why you don't get any matches here.
To match 11 digits anywhere in the string, simply use:
string pattern = #"\d{11}";

Categories

Resources