I can not use boundary (\ b) to validate a word that begins with "@"

7

In the case of / \ b @ MYVAR \ b / i, I can not use boundary, See: link I need to validate a string that contains a @MYVAR (Example) word.

Are there any restrictions on this character? What would be an alternative?

I tested javascript and the result is false.

console.log('/\b@MYVAR\b/i.test("@MYVAR")',/\b@MYVAR\b/i.test("@MYVAR"));

In php the code would look something like this:

<?php
$value = "@MYVAR";
if(preg_match("#/\b@MYVAR\b/i#i", trim($value))){
 echo "ok";
}
    
asked by anonymous 12.07.2017 / 23:23

4 answers

5

The boundary ( \b ) applies only to letters, numbers, and the underline that would be the equivalent of \w ( [a-zA-Z0-9_] ) so its regex fails.

In this case you would have to leave the arroyo outside the boundary. Something like @\buserid\b or @?\buserid\b

    
12.07.2017 / 23:29
4

The problem is that @ is not considered a valid character for word . That is, \b refers to the beginning of a word but the valid characters for \w are [a-zA-Z0-9_] , and @ is not there.

    
12.07.2017 / 23:28
4

Complementing the concept:

The \b does not make selection. It is a anchor as well as ^ and $ and positions the cursor to positions that are between: (^\w|\w$|\W\w|\w\W) . In other words:

  • At the beginning of the string, since the first char is a char word .
  • At the end of the string, since the last char is a char word .
  • In the middle of the string, where char is one word and the other is not

A char word is what is in [a-zA-Z0-9_] , that is, letters, digits, and underlines.

For example: said "i'm looking @ you" , \b would position (I'll mark with | ):

|i|'|m| |looking| @ |you|

I think these considerations may be helpful to some.

    
13.07.2017 / 00:02
2

As quoted by the elder rray and Sergio , a word boundary is defined by starting with [a-z A-Z 1-9] characters, however this can be reversed with a regex like this: / p>

(@\buserid\b)

Explanation:
This regex identifies the @ character and only the match if there is the word "userid".

    
12.07.2017 / 23:50