kcsujeet
kcsujeet

Reputation: 522

Regex for matching everything except multi digit numbers

Can some one provide me with a regex to match everything in a string except a multi digit number?

Example string: a hello 656554 ho5w are you

In the above example the number everything except 656554 should be matched. The digit 5 in how also should be matched.

I tried this: ((?![0-9]{2,}).) But this matched the 4 in 656554 also.

Edit: Here's what I tried. https://regex101.com/r/Jm2GTW/1

Edit 2: Please go through the link above once.

Upvotes: 2

Views: 997

Answers (4)

virolino
virolino

Reputation: 2201

Regex:

\d{2,}

Replace with nothing (i.e. delete).

Test here.

Upvotes: 1

Michał Turczyn
Michał Turczyn

Reputation: 37367

Try \D*(?<=\D|^)\d?(?=\D|$)\D*

Explanation:

\D* - match zero or more non-digits

(?<=\D|^) - poisitve lookbehind: assert what preceds is non-digit or beginning of the strnig ^

\d? - match zero ro one digit

(?=\D|$) - positive lookahead: assert what follows is a non-digit or end of the string $

Demo

Upvotes: 0

Shar1er80
Shar1er80

Reputation: 9041

Based on the data you're actually using, this pattern appeared to work

(\D+\d?\D)

But the strings that have a single digit get broken apart.

Regex Demo

Upvotes: 2

GalAbra
GalAbra

Reputation: 5148

Assuming you want to match each word separately (split by spaces), you can use the following regex:

\b\d\b|\b(?:[^\d\s]*?\d?[^\d\s])+\b

It matches one of two scenarios:

  1. A single digit.
  2. A word consists of no 2 consecutive digits.

Upvotes: 0

Related Questions