I have following statement:
(( { dbo.Document.MimeType_ID in (select ID from MimeType where Name ='PDF')} Or { dbo.WorkflowItem.CurrentStateName not like 'On_Hold%'} ) And ( { dbo.DocumentMetaData.Field_ID=74 And dbo.DocumentMetaData.FieldValue Not like '%test%'} And { dbo.Document.FileName='karan'} ))
I want to 4 statements between {}
eg
dbo.Document.MimeType_ID in (select ID from MimeType where Name ='PDF')
dbo.WorkflowItem.CurrentStateName not like 'On_Hold%'
dbo.DocumentMetaData.Field_ID=74 And dbo.DocumentMetaData.FieldValue Not like '%test%'
dbo.Document.FileName='karan'
This regex will work (if there is no nested pattern)
\{\s*([^}]+)\s*\}
C# Code
string input = "(( { dbo.Document.MimeType_ID in (select ID from MimeType where Name ='PDF')} Or { dbo.WorkflowItem.CurrentStateName not like 'On_Hold%'} ) And ( { dbo.DocumentMetaData.Field_ID=74 And dbo.DocumentMetaData.FieldValue Not like '%test%'} And { dbo.Document.FileName='karan'} ))";
string pattern = "\\{\\s*([^}]+)\\s*\\}";
Regex rgx = new Regex(pattern);
Match match = rgx.Match(input);
while (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
match = match.NextMatch();
}
Ideone Demo
Related
i want to get string data from the paragraph, in string there will a space.
sample data
my id is REG #22334 E112233
my name is xyz
my city is xyz
Expected op = 22334 E112233
code
var myString= "my id is REG #22334 E112233
my name is xyz
my city is xyz";
var regex = new Regex(#"[1-3]\d{4}([ ]E\d{6})?$");
var id= regex.Match(myString).Value;
O/p = "";
Since you match at the end of the line with $ you need to use the multiline option:
var regex = new Regex(#"[1-3]\d{4}(?: E\d{6})?$", RegexOptions.Multiline);
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
var myString= #"my id is REG #22334 E112233
my name is xyz
my city is xyz";
var regex = new Regex(#"[1-3]\d{4}(?: E\d{6})?$", RegexOptions.Multiline);
var id= regex.Match(myString).Value;
Console.WriteLine(id);
}
}
Output:
22334 E112233
My string:
string str = "user:steo id:1 nickname|user:kevo id:2 nickname:kevo200|user:noko id:3 nickname";
Now I want to get the values out with Regex:
var reg = Regex.Matches(str, #"user:(.+?)\sid:(\d+)\s+nickname:(.+?)")
.Cast<Match>()
.Select(a => new
{
user = a.Groups[1].Value,
id = a.Groups[2].Value,
nickname = a.Groups[3].Value
})
.ToList();
foreach (var ca in reg)
{
Console.WriteLine($"{ca.user} id: {ca.id} nickname: {ca.nickname}");
}
I do not know how I can do it with regex that I can use nickname:(the nickname) I only want use the nickname if it has a nickname like nickname:kevo200 and noch nickname
I am not a 100% sure if this answers your question, but i fetched a list from the given input string via regex parsing and either return the nick when available or the username otherwise.
PS C:\WINDOWS\system32> scriptcs
> using System.Text.RegularExpressions;
> var regex = new Regex(#"\|?(?:user(?::?(?<user>\w+))\sid(?::?(?<id>\d*))\s?nickname(?::?(?<nick>\w+))?)");
> var matches = regex.Matches("user:steo id:1 nickname|user:kevo id:2 nickname:kevo200|user:noko id:3 nickname");
> matches.Cast<Match>().Select(m=>new {user=m.Groups["user"].Value,nick=m.Groups["nick"].Value}).Select(u=>string.IsNullOrWhiteSpace(u.nick)?u.user:u.nick);
[
"steo",
"kevo200",
"noko"
]
edit: regex designer: https://regexr.com/3uf8t
edit: improved version to accept escape sequences in nicknames
PS C:\WINDOWS\system32> scriptcs
> using System.Text.RegularExpressions;
> var regex = new Regex(#"\|?(?:user(?::(?<user>\w+))?\sid(?::(?<id>\d*))?\s?nickname(?::(?<nick>[\w\\]+))?)");
> var matches = regex.Matches("user:steo id:1 nickname|user:kevo id:2 nickname:kevo200|user:noko id:3 nickname|user:kevo id:2 nickname:kev\\so200");
> matches.Cast<Match>().Select(m=>new {user=m.Groups["user"].Value,nick=m.Groups["nick"].Value.Replace("\\s"," ")}).Select(u=>string.IsNullOrWhiteSpace(u.nick)?u.user:u.nick);
[
"steo",
"kevo200",
"noko",
"kev o200"
]
Try this: user:(.+?)\sid:(\d+)\s+nickname:*(.*?)(\||$).
At first I proposed this regex: user:(.+?)\sid:(\d+)\s+nickname:*(.*?)\|* – wrong, doesn't capture name because of lazy quantifier.
Then this regex expression: user:(.+?)\sid:(\d+)\s+nickname(:(.+?)|)(\||$) – this should match all the parts divided by '|' in your string and give nickname="" for empty nicknames. But in case Groups[4] is not defined (when nickname is not followed by ":") you'll need check on the value existence.
If it were up to me and the data you are processing is always pipe separated and in a constant order, I would probably just skip the regex and split the string into it's pieces using String.Split like this.
string str = "user:steo id:1 nickname|user:kevo id:2 nickname:kevo200|user:noko id:3 nickname";
var entries = str.Split('|');
foreach(var entry in entries)
{
var subs = entry.Split(' ');
var userName = subs[0].Split(':')[1];
var id = subs[1].Split(':')[1];
var tempNick = subs[2].Split(':');
var nick = tempNick.Length == 2 ? tempNick[1] : string.Empty;
Console.WriteLine(userName + " id:" + id + " nickname " + nick);
}
Without Regex:
static void GetInfo()
{
string input = #"user:steo id:1 nickname|user:kevo id:2 nickname:kevo200|user:noko id:3 nickname";
var users =
from info in input.Split('|')
let x = info.Split(" ")
let nick_split = x[2].Split(':')
let has_nick = nick_split.GetUpperBound(0) > 0
let z = new
{
User = x[0].Split(':')[1],
Id = x[1].Split(':')[1],
Nickname = has_nick ? nick_split[1] : String.Empty
}
select z;
foreach (var user in users)
{
Console.WriteLine($"user: {user.User}, id: {user.Id}, nickname: {user.Nickname}");
}
}
I'm trying to parse messages transmited over TCP for my own network protocol using regex without success.
My commands start with ! followed by COMMAND_NAME and a list of arguments in the format or ARGUMENT_NAME=ARGUMENT_VALUE enclosed in <>
for example:
!LOGIN?<USERNAME='user'><PASSWORD='password'>;
my code :
public class CommandParser
{
private Dictionary<string, string> arguments = new Dictionary<string, string>();
public CommandParser(string input)
{
Match commandMatch = Regex.Match(input, #"\!([^)]*)\&");
if (commandMatch.Success)
{
CommandName = commandMatch.Groups[1].Value;
}
// Here we call Regex.Match.
MatchCollection matches = Regex.Matches(input,"(?<!\\S)<([a-z0-9]+)=(\'[a-z0-9]+\')>(?!\\S)",
RegexOptions.IgnoreCase);
//
foreach (Match argumentMatch in matches)
{
arguments.Add(
argumentMatch.Groups[1].Value,
argumentMatch.Groups[2].Value);
}
}
public string CommandName { get; set; }
public Dictionary<string, string> Arguments
{
get { return arguments; }
}
/// <summary>
///
/// </summary>
public int ArgumentCount
{
get { return arguments.Count; }
}
}
To find the command name, finding the first word after the "!" should be enough:
/\!\w*/g
To match the key/value pairs in groups, you could try something like:
(\w+)='([a-zA-Z_]*)'
An example of the above regex can be found here.
You do not need regex here and avoid them unless that's a last option left. You could do this with simple C# logic.
string input = "!LOGIN?<USERNAME='user'><PASSWORD='password'>";
string command = input.Substring(1, input.IndexOf('?') - 1);
Console.WriteLine($"command: {command}");
var parameters = input
.Replace($"!{command}?", string.Empty)
.Replace("<", "")
.Split(">".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string[] kvpair;
foreach(var kv in parameters) {
kvpair = kv.Split('=');
Console.WriteLine($"pname: {kvpair[0]}, pvalue: {kvpair[1]}");
}
Output:
command: LOGIN
pname: USERNAME, pvalue: 'user'
pname: PASSWORD, pvalue: 'password'
I want to remove subdomain names from a URI.
Example:
I want to return 'baseurl.com' from the Uri "subdomain.sub2.baseurl.com".
Is there a way of doing this using URI class or is Regex the only solution?
Thank you.
This should get it done:
var tlds = new List<string>()
{
//the second- and third-level TLDs you expect go here, set to null if working with single-level TLDs only
"co.uk"
};
Uri request = new Uri("http://subdomain.domain.co.uk");
string host = request.Host;
string hostWithoutPrefix = null;
if (tlds != null)
{
foreach (var tld in tlds)
{
Regex regex = new Regex($"(?<=\\.|)\\w+\\.{tld}$");
Match match = regex.Match(host);
if (match.Success)
hostWithoutPrefix = match.Groups[0].Value;
}
}
//second/third levels not provided or not found -- try single-level
if (string.IsNullOrWhiteSpace(hostWithoutPrefix))
{
Regex regex = new Regex("(?<=\\.|)\\w+\\.\\w+$");
Match match = regex.Match(host);
if (match.Success)
hostWithoutPrefix = match.Groups[0].Value;
}
when i use the code below to get list of groups
i get a long string represent the group name
CN=group.xy.admin.si,OU=Other,OU=Groups,OU=03,OU=UWP Customers,DC=WIN,DC=CORP,DC=com
But i just want to get the group name which is in this case group.xy.admin.si
public static List<string> GetGroups(DirectoryEntry de)
{
var memberGroups = de.Properties["memberOf"].Value;
var groups = new List<string>();
if (memberGroups != null)
{
if (memberGroups is string)
{
groups.Add((String)memberGroups);
}
else if (memberGroups.GetType().IsArray)
{
var memberGroupsEnumerable = memberGroups as IEnumerable;
if (memberGroupsEnumerable != null)
{
foreach (var groupname in memberGroupsEnumerable)
{
groups.Add(groupname.ToString());
}
}
}
}
return groups;
}
There are two options here:
use distinguishedName you got to retrieve group object from AD, use its 'name' attribute
use regex to extract group name
pseudo-code for regular expression:
string Pattern = #"^CN=(.*?)(?<!\\),.*";
string group = Regex.Replace(groupname.ToString(), Pattern, "$1");
groups.Add(group);
Name can contain "," that is escaped by "\", so this regex should work fine even if you have groups named "Foo, Bar"