2

I am trying to make a regex that matches all sub strings under or equal to 2 characters with a space on ether side. What did I do wrong?

ex what I want to do is have it match %2 or q but not 123 and not the spaces.

update this \b\w{2}\b if it also matched one letter sub strings and did not ignore special characters like - or #.

  • Do you mean 1-letter words? Like [`\b\w\b`](https://regex101.com/r/gD2kK4/1)? Could you please clarify with 1 or 2 examples? Have a look at the example of [what your regex matches](https://regex101.com/r/gD2kK4/2). – Wiktor Stribiżew Oct 17 '15 at 15:04
  • @stribizhev no mean one and two letter words but more importantly I can't get it not to match the spaces while using them to id that it is a sub string. –  Oct 17 '15 at 15:05
  • What is your regex flavor? Tool/programming language? – Wiktor Stribiżew Oct 17 '15 at 15:10
  • Please understand that matching and capturing are to different things. This matches `a space, two letters and a space`. You've set it to **not capture** the spaces, but in fact, you aren't capturing anything. You could do the matching part with *lookaround* if your regex flavor supports that. – SamWhan Oct 17 '15 at 15:11
  • oh ok thanks I did not know that. –  Oct 17 '15 at 15:13
  • I do not think nano supports look-behinds, or try `(?<=\s)\w{1,2}(?=\s)` to match 1 or 2 letter words with (white)spaces around. – Wiktor Stribiżew Oct 17 '15 at 15:17
  • no luck it is invalid I can just run `\b\w{2}\b` and `\b\w{1}\b`. thanks –  Oct 17 '15 at 15:21
  • try this - (\b\w{2})|(\w{2}\b) – d-coder Oct 17 '15 at 15:25
  • @stribizhev I just tried it on the file not tester and `\b\w{2}\b` it matches sub strings that look like this `-su#` and does not capture `#f` how can that be fixed? also `(\b\w{2})|(\w{2}\b)` gets stuff in longer sub strings. –  Oct 17 '15 at 15:30
  • I am not getting what you need. Maybe `\b\w{1,2}\b`? Whole 1 or 2 word words? – Wiktor Stribiżew Oct 17 '15 at 16:00
  • @stribizhev So I need to match `1b`, `-b` or `%` but not `-bu` or `abc`. any thing under 3 characters must be matched. –  Oct 17 '15 at 16:12
  • Without a look-behind - [`(^|\s)\S{1,2}(?=\s)`](https://regex101.com/r/xP0kZ4/1) - and if you replace, restore the captured part with $1. – Wiktor Stribiżew Oct 17 '15 at 16:21

1 Answers1

0

You should use

(^|\s)\S{1,2}(?=\s)

Since you cannot use a look-behind, you can use a capture group and if you replace text, you can then restore the captured part with $1.

See regex demo here

Regex breakdown:

  • (^|\s) - Group 1 - either a start of string or a whitespace
  • \S{1,2} - 1 or 2 non-whitespace characters
  • (?=\s) - check if after 1 or 2 non-whitespace characters we have a whitespace. If not, fail.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563