I'm trying to get particular parts from a string. I have to get the part which starts after '@' and contains only letters from the Latin alphabet.
I suppose that I have to create a regex pattern, but I don't know how.
string test = "PQ@Alderaa1:30000!A!->20000";
var planet = "Alderaa"; //what I want to get
string test2 = "@Cantonica:3000!D!->4000NM";
var planet2 = "Cantonica";
There are some other parts which I have to get, but I will try to get them myself. (starts after ':' and is an Integer; may be "A" (attack) or "D" (destruction) and must be surrounded by "!" (exclamation mark); starts after "->" and should be an Integer)
You could get the separate parts using capturing groups:
@([a-zA-Z]+)[^:]*:(\d+)!([AD])!->(\d+)
That will match:
@([a-zA-Z]+)
Match @
and capture in group 1 1+ times a-zA-Z[^:]*:
Match 0+ times not a :
using a negated character class, then match a :
(If what follows could be only optional digits, you might also match 0+ times a digit [0-9]*
)!([AD])!
Match !, capture in group 3 and A or D, then match !->(\d+)
Match ->
and capture in group 4 1+ digitsDemo | C# Demo
You can use this regex, which uses a positive look behind to ensure the matched text is preceded by @
and one or more alphabets get captured using [a-zA-Z]+
and uses a positive look ahead to ensure it is followed by some optional text, a colon, then one or more digits followed by !
then either A
or D
then again a !
(?<=@)[a-zA-Z]+(?=[^:]*:\d+![AD]!)
Demo
C# code demo
string test = "PQ@Alderaa1:30000!A!->20000";
Match m1 = Regex.Match(test, @"(?<=@)[a-zA-Z]+(?=[^:]*:\d+![AD]!)");
Console.WriteLine(m1.Groups[0].Value);
test = "@Cantonica:3000!D!";
m1 = Regex.Match(test, @"(?<=@)[a-zA-Z]+(?=[^:]*:\d+![AD]!)");
Console.WriteLine(m1.Groups[0].Value);
Prints,
Alderaa
Cantonica
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With