skip to Main Content

I’m struggling a bit to get regex put to work to replace the matching pattern.

Some examples of what it should be getting and what not.

During 6 months or in 999 days -> shouldn’t get it

birthdate: π11π -> should get it

Basically, I’m trying to get any non-digit or non-whitespace to afterwards replace it.

I tried using this: [DS]{1}[0-9]+[DS]{1}. For the example birthdate: π11π is working fine, but for during 6 months is also getting matched, when it shouldn’t.

Any suggestions on how to get this to work?

3

Answers


  1. I imagine you would like to delete these chars around numbers as you
    mentioned a "replacement" in your question.

    Using a negative character class should solve your problem. [^ds]
    means "not a space and neither a number". I also imagine you could
    have more than just one character, so you could also replace
    [^ds]{1} (the {1} isn’t useful as it’s already the default
    number of occurrences) by [^ds]+, where + means "1 or several
    times
    " and is equivalent to {1,}.

    You can capture the number in a group so that you can use it for the
    replacement value in order to get rid of the characters before and
    after the number. It leads to:

    /[^ds]+(d+)[^ds]+/g
    

    In action: https://regex101.com/r/Uowh3q/1

    I replaced [0-9] by d (for digit) as it’s a bit shorter.

    Login or Signup to reply.
  2. You can use

    (?<=[^sd])d+(?=[^sd])
    

    See the regex demo. Details:

    • (?<=[^sd]) – a positive lookbehind that matches a location that is immediately preceded with a char other than a whitespace and digit
    • d+ – one or more digits
    • (?=[^sd]) – a positive lookahead that matches a location that is immediately followed with a char other than a whitespace and digit.

    See also a JavaScript demo:

    const arr = ['During 6 months', 'in 999 days', 'birthdate: π11π'];
    const re = /(?<=[^sd])d+(?=[^sd])/;
    for (const s of arr) {
      console.log(s + ' => ' + (s.match(re)?.[0] || 'FALSE'))
    }
    Login or Signup to reply.
  3. D matches such character which is non-digit
    S matches any non-white space character

    So, D & S will not work here. use d & s.

    Now your regex: [DS]{1}[0-9]+[DS]{1}.
    If I correct your regex, it should be:
    [^ds]{1}[0-9]+[^ds]{1} or [^ds]{1}d+[^ds]{1}.

    This is out put of correspoinding regex:
    enter image description here

    If you want to filter the data 11 from result π11π, use regex Lookahead and Lookbehind concept.

    This is pretty much simple:
    (?<=[^ds]{1})[0-9]+(?=[^ds]{1}) or (?<=[^ds]{1})d+(?=[^ds]{1})
    enter image description here

    I think this is better solution for you:

    (?<=[^ds]+)d+(?=[^ds]+)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search