Home > Software design >  Creating a regex that targets only the first line with less than 8 words
Creating a regex that targets only the first line with less than 8 words

Time:01-26

I'm having trouble creating a regular expression that combines two statements.

What I want is to create a regex which targets only the first line of something - ^(.*)$ - and only if it has 8 words or fewer - /^(?:\s*\S (?:\s \S ){0,24})?\s*$/.

I have the individual expressions but I can't seem to join them. Can anyone point me in the direction of where I'm going wrong?

CodePudding user response:

Is there any specific reason for trying to solve this with regular expressions? I feel that this could be achieved easier without regex at all in two steps:

const text = `Lorem ipsum dolor sit amet,
consectetur adipiscing elit, 
sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua.`

const firstLine = text.split("\n")[0]

if (firstLine.split(" ").length <= 8) {
  console.log("First line has 8 or less words")
} else {
  console.log("First line has more than 8 words")
}

Main issue with doing this the way you described is actually "counting" words, I can't see how regex helps in here with this? Is this a hard requirement?

CodePudding user response:

You could try this pattern: /^\s*(\b\w \b\W*){0,8}\n/gi (find 8 words or fewer, follow by a linefeed)

let text = `one two three four five six seven eight
           nine ten eleven twelve`;
let pattern = /^\s*(\b\w \b\W*){0,8}\n/gi;
let matching = text.match(pattern);

CodePudding user response:

you should try this:

^(.*)(?:\s \S ){0,7}\s*$
  • Related