Regexp save / match any word starting with a specific character

I want to save only a line starting with C # or @

  • foobar @sushi - wasabi
  • foobar #sushi - horseradish

Therefore, match only @susui or delete the text around it. PHP or JavaScript.

0
source share
1 answer

Depending on how you define the word, you probably want to

(?<=\s|^)[@#]\S+ 

or

 (?<=\s|^)[@#]\w+ 

Explanation:

 (?<=\s|^) # Assert that the previous character is a space (or start of string) [@#] # Match @ or # \S+ # Match one or more non-space characters (or \w+) # Match one or more alphanumeric characters. 

So in PHP:

 preg_match_all('/(?<=\s|^)[@#]\S+/', $subject, $result, PREG_PATTERN_ORDER); 

gives an $result array of all matches in the string $subject . In JavaScript, this will not work because lookbehinds (the "Assert ..." part from the beginning of the regular expression) are not supported.

+4
source

All Articles