Home > Software engineering >  RegEx find words start Capital letter end colon
RegEx find words start Capital letter end colon

Time:01-07

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

CodePudding user response:

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) \:

CodePudding user response:

To detect word start Capital letter end colon in a string, you can use the following regular expression:

/\b[A-Z][a-z]*:/

This regular expression will match any word that starts with a capital letter and ends with a colon.

For example, in the following string:

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

You can use the following code to extract the words that match the regular expression:

const regex = /\b[A-Z][a-z]*:/;
const matches = myStr.match(regex);

The matches array will contain the following elements:

['Title:', 'Description:', 'Details:', 'Article number:']

CodePudding user response:

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

CodePudding user response:

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

  • Related