Match everything until upcase word

Viewed 77

I want to capture a word placed before another one which is full capitalized

Mister Foo BAR is here        # => "Foo"
Miss Bar-Barz FOO loves cats  # => "Bar-Barz"

I've been trying the following regex: (Mister|Miss)\s([[:alpha:]\s\-]+)(?=\s[A-Z]+), but sometimes it includes the rest of the sentence. For example, it'll return Bar-Barz FOO loves cats instead of Bar-Barz).

  • How can I say, using RegExp, "match every words until the upcase word" ?

  • To clarify the usage of negative lookahead, can we say it "captures until the specified sub-pattern matches, but does not include it to the match data" ?

As a non-native English speaker, apologies if my answer isn't perfectly formulated. Thanks by advance

3 Answers

Match 1+ word chars optionally repeated by a - and 1+ word chars to not match only hyphens or a hyphen at the end.

Assert a space followed by 1+ uppercase chars and a word boundary at the right.

\w+(?:-\w+)*(?=\s[A-Z]+\b)

Explanation

  • \w+ Match 1+ word char
  • (?:-\w+)* Optionally repeat matching - and 1+ word chars
  • (?=\s[A-Z]+\b) Positive lookahead, assert what is directly at the right is 1+ uppercase chars A-Z followed by a word boundary

Regex demo

If there can not be any newlines between the words, you can use [^\S\r\n] instead of \s

\w+(?:-\w+)*(?=[^\S\r\n]+[A-Z]+\b)

Regex demo

I want to capture a word placed before another one which is full capitalized

You may use this regex with a lookahead:

\b\S+(?=[ \t]+[A-Z]+\b)

RegEx Demo

RegEx Description:

  • \b: Word boundadry
  • \S+: Match 1+ non-whitespace characters
  • (?=[ \t]+[A-Z]+\b): Positive lookahead that asserts we have 1+ space and then a word containing only capital letters

You don't say what language you're working in, but the following works for me. The idea is to stop when the parser hits a sequence of uppercase letters/hyphens.

JS example:

let ptn = /(Mister|Miss)\s[\w\-]+(?=\s[A-Z\-]+)/;
"Mister Foo BAR is here".match(ptn); //["Mister Foo", "Mister"]
"Miss Bar-Barz FOO loves cats".match(ptn); //["Miss Bar-Barz", "Miss"]
Related