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
  • 70,371
  • 17
  • 120
  • 139
jogesh_pi
  • 9,477
  • 4
  • 31
  • 61

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
  • 83,228
  • 5
  • 85
  • 113
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
  • 38,175
  • 8
  • 76
  • 97