在 JavaScript 中仅使用正则表达式选择第一个破折号



如何仅选择第一个破折号-和空格之前?

HEllo Good - That is my - first world

我写的正则表达式.+?(?=-)选择了HEllo Good - That is my.

如果我只有字符串HEllo Good - That is my,它看起来不错,但有空格。

var string = 'HEllo Good - That is my - first world';
console.log(string.match(/.+?(?=-)/gm));

如果您只需要第一个破折号,只需使用输入^的开头匹配字符串:

const text = 'HEllo Good - That is my - first world';
const pattern = /^.*?s(-)/;
const match = text.match(pattern);
console.log(`full match: ${match[0]}`);
console.log(`dash only: ${match[1]}`)

如果您需要之前的内容,包括/排除第一个破折号:

const text = 'HEllo Good - That is my - first world';
const patternIncludeDash = /(^.*?s-)/;
const patternExcludeDash = /(^.*?s)-/;
console.log('before the dash, but include dash: ' + text.match(patternIncludeDash)[1]);
console.log('before the dash, but exclude dash: ' + text.match(patternExcludeDash)[1]);

最新更新