0

I am trying to get the word with the following:

$string = 'code 10OFF75 +EXTRA';
$regex  = '/(?<=code)\s\w+/';

Output (tried at rubular.com):

10OFF75

I want to skip the special character with the word code. Say, I have the string code: | code- | code:- then how do I grab the next word?

Amal Murali
  • 73,160
  • 18
  • 123
  • 143
jogesh_pi
  • 9,652
  • 4
  • 34
  • 64

2 Answers2

3

You can try to use the \K feature that removes all on the left from match result:

/code\W+\K\w+/
Casimir et Hippolyte
  • 85,718
  • 5
  • 90
  • 121
2

What Casimir said (recommended for PCRE)... and other options for the road, in case you find yourself other languages that don't have \K support some day:

With lookbehind

(?<=code\W+)\w+

This will work in .NET and Python's regex module, which have infinite-width lookbehind.

With capturing groups

code\W+(\w+)

The parentheses capture the match to group 1. This works in JavaScript (which doesn't support lookbehind) and most other Perl-style engines.

Community
  • 1
  • 1
zx81
  • 39,708
  • 9
  • 81
  • 104