C# Regular Expressions, string between single quotes
Something like this should do it:
string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";
Match match = Regex.Match(val, @"'([^']*)");
if (match.Success)
{
string yourValue = match.Groups[1].Value;
Console.WriteLine(yourValue);
}
Explanation of the expression '([^']*)
:
' -> find a single quotation mark
( -> start a matching group
[^'] -> match any character that is not a single quotation mark
* -> ...zero or more times
) -> end the matching group
C# Regex: matching anything between single quotes (except single quotes)
Try:
= '([^']*)'
Meaning you want anything/everything from = ' that isn't a single quote up to a single quote.
Python example:
import re
text = "attribute = 'some value'"
match = re.search("= '([^']*)'", text)
print(match.group(1))
To read more about that, it is called a negated character class: https://www.regular-expressions.info/charclass.html
C# regex extract string enclosed into single quotes
Your pattern needs an update with yet another alternative branch: '[^'\\]*(?:\\.[^'\\]*)*'
.
It will match:
'
- a single quote[^'\\]*
- 0+ chars other than'
and\
(?:
- a non-capturing group matching sequences of:\\.
- any escape sequence[^'\\]*
- 0+ chars other than'
and\
)*
- zero or more occurrences'
- a single quote
In C#:
string pattern = @"('[^'\\]*(?:\\.[^'\\]*)*'|<=|>=|!=|=|>|<|\)|\(|\s+)";
See the regex demo
C# demo:
var filter = @"abc = 'def' and size = '1 x(3"" x 5"")' and (name='Sam O\'neal')";
var pattern = @"('[^'\\]*(?:\\.[^'\\]*)*'|<=|>=|!=|=|>|<|\)|\(|\s+)";
var tokens = Regex.Split(filter, pattern).Where(x => !string.IsNullOrWhiteSpace(x));
foreach (var tok in tokens)
Console.WriteLine(tok);
Output:
abc
=
'def'
and
size
=
'1 x(3" x 5")'
and
(
name
=
'Sam O\'neal'
)
Regex - Single quotes OR Double quotes -C#
You can use a pattern like this:
href=(["'])(.*?)\1
This will match any string of that contains href=
followed by a "
or '
followed by any number of characters (non-greedily) followed by the same character that was matched previously in group 1. Note that \1
is a backreference.
Also note that this will also mean the contents of your attribute will be captured in group 2 rather than group 1.
Now, the correct way to escape this string literal would be either like this (using regular strings):
Regex.Match(value, "href=([\"'])(.*?)\\1", RegexOptions.Singleline);
Or like this (using verbatim strings):
Regex.Match(value, @"href=([""'])(.*?)\1", RegexOptions.Singleline);
Delimited string regex exclude match inside quotes
You can use lookaround like this.
Regex: (?<=\s)([$]{1,2})[^\$]*\1(?=\s)
Explanation:
(?<=\s)
is positive lookbehind for whitespace
to check if previous character was a whitespace. If '
is present then it won't match.
([$]{1,2})[^\$]*\1
matches word between $
or $$
.
([$]{1,2})
catches $
or $$
and matches it for second time at end of word using capturing group \1
.
[^\$]*
matches word until a $
is found.
(?=\s)
checks for presence of white space after word.
Replacement: Replace with whatever word you wish to.
Regex101 Demo
Update: For the cases like below where words appear at beginning or end.
$Hello$ The $quick$ brown '$$fox$$' jumps $$over$$ the '$lazy$' dog $Hello$
Use this regex.
Regex: (?:(?<=\s)|(?<=^))([$]{1,2})[^\$]*\1(?=\s|$)
(?:(?<=\s)|(?<=^))
looks behind for whitespace
or beginning of string.
(?=\s|$)
looka ahead for whitespace
or end of string.
Regex101 Demo
Regex For singlequote and doublequote
The following RegEx is for Single Quotation sign + Some Texts + Single Quotation sign ('asdasdasdass'):
Regex regexString = new Regex(@"'[^']*'");
The following RegEx is for Double Quotation sign + Some Texts + Double Quotation sign ("asdasdasdass"):
Regex regexString = new Regex(@"""[^""]*""");
Regex to extract string between quotes
Use positive lookbehind operator:
GroupCollection ids = Regex.Match(nodeValue, "(?<=ID=\")[^\"]*").Groups;
You also used a capturing group (the parenthesis), this is why you get 2 results.
C# Regex to remove single quotes between single quotes
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
string str = "begin:'this is an 'example' text'";
str = Regex.Replace(str, "(?<=')(.*?)'(?=.*')", "$1");
Console.WriteLine(str);
}
}
Test this code here.
Related Topics
Is There a Reasonable Approach to "Default" Type Parameters in C# Generics
Why Do Members of a Static Class Need to Be Declared as Static? Why Isn't It Just Implicit
Overloaded Method-Group Argument Confuses Overload Resolution
Configureawait Pushes the Continuation to a Pool Thread
How to Ignore Ssl_Client_Socket_Impl.Cc(1061)] Handshake Failed in Selenium C# Chromedriver
How to Implement a Rule Engine
Startup.Cs in a Self-Hosted .Net Core Console Application
(.1F+.2F==.3F) != (.1F+.2F).Equals(.3F) Why
How to Mix Colors "Naturally" with C#
Right Way to Dispose Image/Bitmap and Picturebox
How to Get the Local MAChine Name in C#
Is There a C# Generic Constraint for "Real Number" Types
Windows Forms Graphic Issue on Windows 10 Os
Strange Behaviour of Console.Readkey() with Multithreading
Install to Same Path When Upgrading Application