我正在寻找字符串中的customerID号码。客户ID将采用此格式customerID{id}
所以看看我会有的一些不同的字符串
myVar = "id: 1928763783.Customer Email: test@test.com.Customer Name:John Smith.CustomerID #123456.";
myVar = "id: 192783.Customer Email: test1@test.com.Customer Name:Rose Vil.CustomerID #193474.";
myVar = "id: 84374398.Customer Email: test2@test.com.Customer Name:James Yuem.";
理想情况下,我希望能够检查是否存在CustomerID。如果确实存在,那么我想看看它是什么。我知道我们可以使用regext但不确定那个样子 感谢
答案 0 :(得分:3)
var match = myVar.match(/CustomerID #(\d+)/);
if (match) id = match[1];
答案 1 :(得分:0)
我不是100%熟悉语法,但我会说:“(CustomerID#([0-9] +)。)”
我认为这是你正在寻找的有效正则表达式,它会检查一个字符串是否有'CustomerID'后跟一个空格,一个数字符号然后是一系列数字。通过用括号括起数字,如果发现了某些内容,可以通过重新括号2来捕获它们
我不确定括号或句点是否需要在此语法之前使用\或它们。对不起,我无法提供更多帮助,但我希望这会有所帮助。
答案 2 :(得分:0)
四处游戏以满足您的需求:
// case-insensitive regular expression (i indicates case-insensitive match)
// that looks for one of more spaces after customerid (if you want zero or more spaces, change + to *)
// optional # character (remove ? if you don't want optional)
// one or more digits thereafter, (you can specify how long of an id to expect with by replacing + with {length} or {min, max})
var regex = /CustomerID\s+#?(\d+)/i;
var myVar1 = "id: 1928763783.Customer Email: test@test.com.Customer Name:John Smith.CustomerID #123456.";
var match = myVar1.match(regex);
if(match) { // if no match, this will be null
console.log(match[1]); // match[0] is the full string, you want the second item in the array for your first group
}