How can I only match a leading space followed by a non numeric in Regex

Viewed 76

I need some assistance, I have been at this for hours now. I am not winning.

I need to match a space only if its followed by a non-numeric character (which I will replace with blank to remove it from the string).

I have tried this ^[^\s+]+\D and it works to some extent.

if I have the string " JLABCD-1 836397-BTD56517" it return correctly without the leading space, which is what I want "JLABCD-1 836397-BTD56517"

if I have " BefhMS JLZARL-1 836397-BTD56517" it returns this "JLZARL-1 836397-BTD56517"

But if I don't have a space before the the first word, I want it to ignore all other spaces.

If I have "_JLABCD-1 836397-BTD56517", I want to return "JLABCD-1 836397-BTD56517" or the original string as it is. Not "836397-BTD56517" which is what I am getting at the moment.

Is this possible with Regex?

2 Answers

Use a look ahead:

"^ +(?=\D)"

but it seems you just want to match any leading spaces. If so, just use:

"^ +"

The negated (due to its first character being ^) character class [^\s+] in your regex matches anything not whitespace or a +.

Use

^\s+(\D)

Replace with $1, it is a backreference to the capturing group (\D). Or \1 if $1 does not work.

See proof.

Explanation

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    \D                       non-digits (all but 0-9)
--------------------------------------------------------------------------------
  )                        end of \1
Related