2

I'm new to RegEx and JavaScript and I was wondering if anyone knew what the RegEx would be for detecting word start Capital letter end colon:

**Example string:

 const myStr=`Title: Consectetur adipiscg elit  Description: Sed sit
 amet eros diam Details: Vestibulum a eros ut massa interdum
 consectetur  Article number: AYHMNR`;

Result:

Title,Description,Details, Article number

I used:

/[:]/i and \b[A-Z(...)].*?\b here

Aleksandar
  • 844
  • 1
  • 8
  • 18
Alli Mam
  • 23
  • 4

4 Answers4

3

You might use:

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

Explanation

  • \b A word boundary to prevent a partial word match
  • [A-Z]\w* Match an uppercase char A-Z and optional word chars
  • (?:\s+[A-Z]\w*)* Optionally repeat words that start with an uppercase char
  • (?:\s+[a-z]\w*)* Optionally repeat matching words that start with a lowercase char a-z
  • (?=:) Positive lookahead, assert : directly to the right of the current position

See a regex101 demo.

Note that \s can also match a newline.

An example matching spaces without newlines using [^\S\n]* instead of \s*

const regex = /\b[A-Z]\w*(?:[^\S\n]+[A-Z]\w*)*(?:[^\S\n]+[a-z]\w*)*(?=:)/g;
const s = `Title: Consectetur adipiscg elit  Description: Sed sit
> amet eros diam Details: Vestibulum a eros ut massa interdum
> consectetur  Article number: AYHMNR
Title tEST: testing
Big red car:1, Small green ship: 2, Green Forest:3`;
console.log(s.match(regex))
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
1

You’ll need to at least target the colon to achieve what you’re looking for. How about something like this:

(\b[A-Z].*?\b)+\:
Jordan
  • 1,390
  • 2
  • 9
  • 24
1
const myStr = 'Title: Consectetur adipiscg elit  Description: Sed sit amet eros diam Details: Vestibulum a eros ut massa interdum consectetur  Article number: AYHMNR';
const regex = /([A-Z]{1}[a-z]+(?:\s[a-z]+)?):/g;
const getFirstGroup = () => {
  return Array.from(myStr.matchAll(regex), m => m[1]);
}

for (const match of getFirstGroup()) {
  console.log(match);
}

Output:

Title
Description
Details
Article number
Joan Lara
  • 1,362
  • 8
  • 15
  • how can i find ``` let strA = '10Send Me11Send Me12Send Me13Send Me14Send Me15Only 1 left16Send Me'``` number between ME and ONLY words – Alli Mam Feb 09 '23 at 18:21
1

Here’s a simple example with the lookahead assertion so you don’t get the colon in the result.

[A-Z][a-z\s]*(?=\:)

https://rubular.com/r/3PTi0J3BSapk5F

Starts with a capital letter followed by any number of lowercase letters or space and then followed by a colon with a lookahead assertion. For more information on look ahead see this SO answer: https://stackoverflow.com/a/3926546

petegordon
  • 339
  • 1
  • 9