Home > Mobile >  Match everything except the digit and space in the very beginning
Match everything except the digit and space in the very beginning

Time:04-02

The target string looks like a number followed by a space and then followed by one or more letters, e.g. 1 Foo or 2 Foo bar.

I can use [^\d\s]. , but it doesn't work for single letters, e.g. 3 A.

What can be done here?

https://regexr.com/6io06

The workaround I use currently is to use replacing instead of matching.

from  \d\s(. )
to    $1

But as a purist I prefer to use replacing if and only if we don't mean "replace something with nothing". When we need to replace something with nothing, I would prefer to use matching.

CodePudding user response:

I prefer using a regex replacement here:

var input = ["1 Foo", "2 Foo Bar", "No Numbers Here"];
var output = input.map(x => x.replace(/^\d  /, ""));
console.log(output);

CodePudding user response:

Just remove the square brackets. The square brackets alone indicate "any of this set", so you are matching either \d or \s. When you also add a ^ inside you are not indicating the beginning of the string, but you are negating the set. So, summing up, your regular expression means:

Match a single character that may be everything except a digit and a white space, then match everything.

If you remove the square brackets you will match \d followed by \s, and the ^ symbol will mean "beginning of the string".

/^\d\s(. )/

CodePudding user response:

If I didn't misread your question, this might be what you want:
exclude capture the number and space at the beginning

https://regexr.com/6io1m

(?!^\d )(?!\s ).*

This matches 1 Foo Bar to Foo Bar and 3 A to A

CodePudding user response:

You don't have to use replace. You can optionally match a digit and a space at the start of the string with ^(?:\d )? and capture the rest of the line in group 1 that starts with a letter.

Note that if you want to use \s that is could also match a newline.

^(?:\d  )?([A-Za-z].*)

Regex 101 demo

const regex = /^(?:\d  )?([A-Za-z].*)/;

["1 Foo", "2 Foo bar", "Test", "3 A", "-test-"]
.forEach(s => {
  const m = s.match(regex);
  if (m) console.log(m[1])
});

  • Related