1

Well, I don't know how to explain that exactly, but I have this text:

abc=0;def=2;abc=1;ghi=4;jkl=2

The thing I want to do is select abc=0 and abc=1 but excluding abc part...

My regex is: abc=\d+, but it includes abc part...

I readed something about this, and the answer was this: (?!abc=)\d+ but It select all the numbers inside the text...

So, can somebody help me with this?

Thanks in advance.

Community
  • 1
  • 1
z3nth10n
  • 2,341
  • 2
  • 25
  • 49

2 Answers2

3

If your language supports \K then you could use the below regex to matche the number which was just after to the string abc=,

abc=\K\d+

DEMO

OR

use a positive look-behind if your language didn't support \K,

(?<=abc=)\d+

DEMO

C# code would be,

{
string str = "abc=0;def=2;abc=1;ghi=4;jkl=2";
Regex rgx = new Regex(@"(?<=abc=)\d+");
 foreach (Match m in rgx.Matches(str))
Console.WriteLine(m.Value);
}

IDEONE

Explanation:

  • (?<=abc=) Positive lookbehind which actually sets the matching marker just after to the string abc=.
  • \d+ Matches one or more digits.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Oh, thanks you solve my question... I have to learn regex correctly! :P – z3nth10n Jul 14 '14 at 14:50
  • @user3286975 added some info :-) – Avinash Raj Jul 14 '14 at 14:55
  • I readed something of this before, because I remembered that in the last part we have to use `(?=[\w+])` and in the first part `(?<=[\w+])`, why? :P Thanks for everything – z3nth10n Jul 14 '14 at 15:04
  • `(?=)` is called positive look-behind. And `+` must be came just outside the character class so your regex would be `(?=[\w]+)` , `(?<=[\w]+)` .This pattern `(?=[\w+])` means follow up character must be a word character or a literal `+` – Avinash Raj Jul 14 '14 at 15:07
2

You don't need a lookaround assertion here. You can simply use a capturing group to capture the matched context that you want and refer back to the matched group using the Match.Groups Property.

abc=(\d+)

Example:

string s = "abc=0;def=2;abc=1;ghi=4;jkl=2";
foreach (Match m in Regex.Matches(s, @"abc=(\d+)"))
         Console.WriteLine(m.Groups[1].Value);

Output

0
1
hwnd
  • 69,796
  • 4
  • 95
  • 132
  • +1, OP said C# which means either lookbehind or capture group, but not `\K` which is not supported in .NET. – zx81 Jul 15 '14 at 00:57