Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: word boundary but for white space, beginning of line or end of line only

Tags:

regex

I am looking for some word boundary to cover those 3 cases:

  1. beginning of string
  2. end of string
  3. white space

Is there something like that since \b covers also -,/ etc.?

Would like to replace \b in this pattern by something described above:

(\b\d*\sx\s|\b\d*x|\b)
like image 457
Marcin Avatar asked Oct 26 '10 17:10

Marcin


People also ask

How do you match a word boundary in regex?

Word Boundary: \b The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).

What does \b mean in regular expression?

Matches only at the start of the string. \b. Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of word characters. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string.

What is the difference between \b and \b in regular expression?

Using regex \B-\B matches - between the word color - coded . Using \b-\b on the other hand matches the - in nine-digit and pass-key .

How do I match a character except space in regex?

[^ ] matches anything but a space character.


1 Answers

Try replacing \b with (?:^|\s|$)

That means

(
  ?: don't consider this group a match
  ^   match beginning of line
  |   or
  \s  match whitespace
  |   or
  $   match end of line
)

Works for me in Python and JavaScript.

like image 97
Michael Avatar answered Oct 21 '22 19:10

Michael