1

I'm formatting a datetime string in javascript by Regex, so I want:

  1. Find and replace all d characters when d is not within other alphabetic characters. like this: enter image description here

  2. Find and replace all dd characters when dd is not within other alphabetic characters. like this: enter image description here


I tested /\bd\b/mg pattern but its result is not which I want everytime.

How should I exclude unwanted cases in the following command:

str = str.replace(/\bd\b/mg, number);
Ramin Bateni
  • 16,499
  • 9
  • 69
  • 98

2 Answers2

1

The regular expression You posted does not consider _ as a word boundary, so it does not replace the character as expected.

In order to include this character as well, either before or after the d character to be replaced, You can use expressions similar to these:

  1. To replace d:

    /(\b|_)(d)(\b|_)/mg
    
  2. To replace dd:

    /(\b|_)(dd)(\b|_)/mg
    

Or to replace both in the same way (if it's acceptable):

    /(\b|_)(d|dd)(\b|_)/mg

In comments under this answer in another thread on StackOverflow, it was also suggested to use a library that can format dates, instead of implementing it by Yourself.

UPDATE: As someone mentioned, the issue with this is also that including _ in the regular expression, removes it after the replacement. However, You can call replace and use capturing parentheses references, like this:

    str.replace(/(\b|_)(d)(\b|_)/mg, "$1" + number + "$3")

I've updated earlier expressions posted in this answer to work with this method.

Please note that I'm not aware of all the cases You want to consider, so if You have any problems using the suggested solution or it does not work as expected in Your case, please let me know, so I can try to help.

Community
  • 1
  • 1
Lukasz M
  • 5,635
  • 2
  • 22
  • 29
  • 1
    Now, with your last fix in this answer that is about preventing `_` replacement in the final result, it works fine. Thank you. – Ramin Bateni Nov 30 '16 at 22:08
1

I could use a lookahead and if you are not using JavaScript then a lookbehind as well.

example lookahead which checks if there is no following alpha character:

(?=[^a-zA-Z])

If you are using JavaScript it doesn't support lookbehind so you will need to use a capturing group and backreferencing.

For JS capture the part in the outermost parentheses and then use \1, \2... to target:

[^a-zA-Z](d(?=[^a-zA-Z]))

non-JS can use lookbehind:

(?<=[^a-zA-Z])d(?=[^a-zA-Z])
haltersweb
  • 3,001
  • 2
  • 13
  • 14