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
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 defaultnumber of occurrences) by
[^ds]+
, where+
means "1 or severaltimes" 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:
In action: https://regex101.com/r/Uowh3q/1
I replaced
[0-9]
byd
(for digit) as it’s a bit shorter.You can use
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 digitd+
– 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:
D matches such character which is non-digit
S matches any non-white space character
So,
D
&S
will not work here. used
&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:
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})
I think this is better solution for you:
(?<=[^ds]+)d+(?=[^ds]+)