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

时间:2018-06-30 08:28:36

标签: javascript regex

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

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));

1 个答案:

答案 0 :(得分:2)

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

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]);