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

标签 javascript regex

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

你好 - 那是我的 - 第一个世界

我编写的正则表达式.+?(?=-)选择了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]);

关于javascript - 仅使用 JavaScript 中的正则表达式选择第一个破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51113181/

相关文章:

javascript - jQuery 中的 AND/OR 条件

javascript - 练习二维数组

regex - Grep 特定字符之前的所有内容

javascript - 使用加速度计检测震动,然后激活老虎机

javascript - 如何调试在 Razor View 中定义的模态对话的 document.ready Javascript?

javascript - 中止ajax调用javascript

javascript - 匹配带空格和不带空格的模式

sql - 如何在 PL/SQL 中分割字符串而不截断单词?

php - 正则表达式错误 preg_replace_callback() : Unknown modifier '.' in

sql - 在 MySQL 的正则表达式中使用列