-1

我正在字符串中查找单词 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 是否存在。如果它确实存在,那么我想看看它是什么。我知道我们可以使用正则表达式,但不确定看起来如何谢谢

4

3 回答 3

3
var match = myVar.match(/CustomerID #(\d+)/);
if (match) id = match[1];
于 2012-11-06T00:28:58.577 回答
0

我不是 100% 熟悉语法,但我会说:“(CustomerID #([0-9]+).)”

我认为这是您要查找的有效正则表达式,它将检查字符串是否具有“CustomerID”后跟空格、数字符号和数字序列。通过用括号包围数字,如果发现某些东西,可以通过引用括号 2 来捕获它们

我不确定括号或句点在这种语法中是否需要在它们之前添加一个 \ 。抱歉,我无法提供更多帮助,但我希望这在某种程度上有所帮助。

于 2012-11-06T00:35:46.410 回答
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
}
于 2012-11-06T00:37:38.157 回答