regex 如何在javascript中使用正则表达式提取破折号之间的字符串?

dhxwm5r4  于 2023-03-31  发布在  Java
关注(0)|答案(5)|浏览(111)

在JavaScript中有一个字符串:

const str = "bugfix/SOME-9234-add-company"; // output should be SOME-9234
 const str2 = "SOME/SOME-933234-add-company"; // output should be SOME-933234
 const str3 = "test/SOME-5559234-add-company"; // output should be SOME-5559234

我想提取SOME-..直到第一个-字符。
我使用了这个正则表达式,但没有工作。什么是正确的正则表达式?

const s = "bugfix/SOME-9234-add-company";
const r1 = s.match(/SOME-([1-9])/);
const r2 = s.match(/SOME-(.*)/);
const r3 = s.match(/SOME-(.*)-$/);

console.log({ r1, r2, r3 });
4bbkushb

4bbkushb1#

const s = "bugfix/SOME-9234-add-company";

// This one is close, but will return only one digit 
console.log( s.match(/SOME-([1-9])/) );
// What you wanted:
console.log( s.match(/SOME-([1-9]+)/) ); // note the +, meaning '1 or more'

// these are also close. 
// This'll give you everything after 'SOME':
console.log( s.match(/SOME-(.*)/) );
// This'll match if the line 'ends with -' (= -$)
console.log( s.match(/SOME-(.*)-$/) );
 
//What you wanted:
console.log( s.match(/SOME-(.*?)-/) ); // Not end of line, but 'ungreedy'(the ?) which does 'untill the first - you encounter'

// instead of Using [1-9], you can also use \d, digits, for readability:
console.log( s.match(/SOME-(\d+)/) );
kognpnkq

kognpnkq2#

您可以使用/(SOME-[\d]+)/g正则表达式,* 例如 *

const strings = [
  "bugfix/SOME-9234-add-company", // output should be SOME-9234
  "SOME/SOME-933234-add-company", // output should be SOME-933234
  "test/SOME-5559234-add-company" // output should be SOME-5559234
];
strings.forEach(string => {
  const regex = /(SOME-[\d]+)/g;
  const found = string.match(regex);
  console.log(found[0]);
});
tktrz96b

tktrz96b3#

/(SOME-[^-]+)/应该工作得很好。(捕获SOME-后不是连字符的所有内容)
或者,如果你知道你只有数字,接近你所尝试的:
/(SOME-[1-9]+)/
您缺少一个+,无法使用多个字符。
我还修改了括号,以准确地捕捉您在问题中显示的内容(即,包括带有SOME的部分)

z31licg0

z31licg04#

如果你不想使用正则表达式,那么这很简单

const s = "bugfix/SOME-9234-add-company";
const str2 = "SOME/SOME-933234-add-company";
const str3 = "test/SOME-5559234-add-company";
const r1 = s.split("/")[1].split("-",2).join("-"); // "SOME-9234"
const r2 = str2.split("/")[1].split("-",2).join("-"); // "SOME-933234"
const r3 = str3.split("/")[1].split("-",2).join("-"); // "SOME-5559234"
czfnxgou

czfnxgou5#

在你尝试的模式中:

  • $声明字符串的结尾,
  • [1-9]匹配不带0的单个数字1-9
  • .*将匹配任何没有换行符的字符0+次

不需要捕获组,您可以匹配:

\bSOME-\d+

参见regex demo
请注意,match将返回一个数组,您可以从中获取索引0。

[
  "bugfix/SOME-9234-add-company",
  "SOME/SOME-933234-add-company",
  "test/SOME-5559234-add-company"

].forEach(s => console.log(s.match(/\bSOME-\d+/)[0]));

相关问题