Regex starting with a string - c#

I want to filter the following string with the regular expressions:
TEST^AB^^HOUSE-1234~STR2255
I wanna get only the string "HOUSE-1234" and I've to test the string always with the beginning "TEST^AB^^" and ending with the "~".
Can you please help me how the regex should look like?

You can use \^\^(.*?)\~ pattern which matches start with ^^ and ends with ~
string s = #"TEST^AB^^HOUSE-1234~STR2255";
Match match = Regex.Match(s, #"\^\^(.*?)\~", RegexOptions.IgnoreCase);
if (match.Success)
{
string key = match.Groups[1].Value;
Console.WriteLine(key);
}
Output will be;
HOUSE-1234
Here is a DEMO.

string input = "TEST^AB^^HOUSE-1234~STR2255";
var matches = Regex.Matches(input, #"TEST\^AB\^\^(.+?)~").Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToList();

string pattern=#"\^\^(.*)\~";
Regex re=new Regex(pattern);

With the little information you've given us (and assuming that the TEST^AB isn't necessarily constant), this might work:
(?:\^\^).*(?:~)
See here
Or if TEST^AB is constant, you can throw it in too
(?:TEST\^AB\^\^).*(?:~)
The important part is to remember that you need to escape the ^

Don't even need the RegEx for something that well defined. If you want to simplify:
string[] splitString;
if (yourstring.StartsWith("TEST^AB^^"))
{
yourstring = yourstring.Remove(0, 9);
splitString = yourstring.Split('~');
return splitString[0];
}
return null;

(TEST\^AB\^\^)((\w)+-(\w+))(\~.+)
There are three groups :
(TEST\^AB\^\^) : match yours TEST^AB^^
((\w)+\-(\w+)) : match yours HOUSE-123
(\~.+) : match the rest

You should do this without regex:
var str = "TEST^AB^^HOUSE-1234~STR2255";
var result = (str.StartsWith("TEST^AB^^") && str.IndexOf('~') > -1)
? new string(str.Skip(9).TakeWhile(c=>c!='~').ToArray())
: null;
Console.WriteLine(result);

Related

Regex for this formula

I'm struggling with making a regex for this type of formula: LU1O/00054362/8. I'd like to receive only the first part - LU1O every time. It's always letter, letter, number, letter. Please help me with suggestion.
try this:
string input = #"LU1O/00054362/8";
var regex = "^[A-Z]{2}[0-9][A-Z]$";
var match = Regex.Match(input.Substring(0,4), regex, RegexOptions.IgnoreCase);
if (match.Success)
{
//matched
}
or
string input2 = #"LU1O/00054362/8";
var regex2= "^[A-Z]{2}[0-9][A-Z]";
var match2 = Regex2.Match(input2, regex2, RegexOptions.IgnoreCase);
if (match2.Success)
{
//matched
}
If '/' is always a delimiter you could string.split('/') and access the first element from the resulting array.

Regular expression to extract based on capital letters

Hi please can someone help with a C# regex to split into just two words as follows:
"SetTable" ->> ["Set", "Table"]
"GetForeignKey" ->> ["Get", "ForeignKey"] //No split on Key!
This can be solved in different ways; one method is the following
string source = "GetForeignKey";
var result = Regex.Matches(source, "[A-Z]").OfType<Match>().Select(x => x.Index).ToArray();
string a, b;
if (result.Length > 1)
{
a = source.Substring(0, result[1]);
b = source.Substring(result[1]);
}
Try the regex below
(?![A-Z][a-z]+Key)[A-Z][a-z]+|[A-Z][a-z]+Key
c# code
var matches = Regex.Matches(input, #"(?![A-Z][a-z]+Key)[A-Z][a-z]+|[A-Z][a-z]+Key");
foreach (Match match in matches)
match.Groups[0].Value.Dump();
for Splitting
matches.OfType<Match>().Select(x => x.Value).ToArray().Dump();
Fiddle

Regex - replacing chars in C# string in specific cases

I want to replace all brackets to another in my input string only when between them there aren't digits. I wrote this working sample of code:
string pattern = #"(\{[^0-9]*?\})";
MatchCollection matches = Regex.Matches(inputString, pattern);
if(matches != null)
{
foreach (var match in matches)
{
string outdateMatch = match.ToString();
string updateMatch = outdateMatch.Replace('{', '[').Replace('}', ']');
inputString = inputString.Replace(outdateMatch, updateMatch);
}
}
So for:
string inputString = "{0}/{something}/{1}/{other}/something"
The result will be:
inputString = "{0}/[something]/{1}/[other]/something"
Is there possibility to do this in one line using Regex.Replace() method?
You may use
var output = Regex.Replace(input, #"\{([^0-9{}]*)}", "[$1]");
See the regex demo.
Details
\{ - a { char
([^0-9{}]*) - Capturing group 1: 0 or more chars other than digits, { and }
} - a } char.
The replacement is [$1], the contents of Group 1 enclosed with square brackets.
Regex.Replace(input, #"\{0}/\{(.+)\}/\{1\}/\{(.+)}/(.+)", "{0}/[$1]/{1}/[$2]/$3")
Could you do this?
Regex.Replace(inputString, #"\{([^0-9]*)\}", "[$1]");
That is, capture the "number"-part, then just return the string with the braces replaced.
Not sure if this is exactly what you are after, but it seems to fit the question :)

How can I get a certain segment with regex?

I have a simple string
testteststete(segment1)tete(segment2)sttes323testte(segment3)eteste
I need to get (segment2). Each segment may be any text. I tried to use this regex
\(.+\). But i get this result
How i can get (segment2)?
PS: I want to get all of the segments in brackets
In C#, you can just match all the (...) substrings and then access the second one using Index 1:
var rx = #"\([^)]*\)";
var matches = Regex.Matches(str, rx).Cast<Match>().Select(p => p.Value).ToList();
var result = matches != null && matches.Count > 1 ? matches[1] : string.Empty;
See IDEONE demo
The regex matches
\( - an opening (
[^)]* - 0 or more characters other than )
\) - a closing ).
I can't test it but this should probably work:
\([^\)]*\)
You can try to use this regex:
\(([^)]+)\)
REGEX DEMO
(?<=^[^()]*\([^)]*\)[^()]*\()[^)]*
You can simply use this.See Demo
var regex = new Regex(#"\(([^)]*)\)", RegexOptions.Compiled);
string secondMatch = regex.Matches(text).Cast<Match>()
.Select(m => m.Value.Trim('(', ')'))
.ElementAtOrDefault(1);

Regular expression to replace

I heard it's possible to use regular expression to replace. I have following scenario where I would like to remove index number semicolon and pound sign.
(Index Number;#)
For example 521;#SouthWest Region
after expression it should be Southwest Region
I tried many variation ((?<=^.*?;).* OR ^.*?; ) but not working.
Regex.Replace("521;#SouthWest Region", #"\d+;#", "");
// results SouthWest Region
Ctrl+Shift+H Find what: (.*)\;\#{.*} Replace with: \1
Try this:
public void Replace()
{
var myString = "(In£dex N#£umber;#)";
var replacement = String.Empty;
var regExPattern = #"\d|[#£;]";
var regEx = new Regex(regExPattern);
var result = regEx.Replace(myString, replacement);
Console.WriteLine("The replaced string: {0}", result);
}
Edit: Ooops, sorry, i think I missunderstod your question.
Edit 2: Replace the above code with: var regExPattern = #"\d|[#£;]";

Categories