簡體   English   中英

檢查字符串中的特定 substring 模式並獲取其所有匹配項

[英]Check for a particular substring pattern within a string and get all of its matches

我正在嘗試在字符串中搜索並嘗試從字符串中提取特定內容。 這是我要解決的示例。

const string = 'xtyzjdjgdjf +91888123455, +918885558565 +916885123456, +911234569870'
i am trying to extract only '+91888123455, +918885558565 +916885123456, +911234569870'

但這個數字是動態的,它會根據響應而變化

關於使用的正則表達式的模式... /\+\d+,{0,1}/g ...

  1. \+ ... 匹配單個強制+符號... 后跟...
  2. \d+ ...至少一個數字(或數字序列)...后跟...
  3. ,{0,1} ... 單個但可選的逗號。
  4. g ... 全局搜索/匹配模式。

 function extractValidNumberSequences(str) { return str.match(/\+\d+,{0,1}/g).join(' '); } const test = ` xtyzjdjgdjf +91888123455, +918885558565 +916885123456,,, +91123456987 dsjk jjd sag sadgsadj 43865984 dsjghj, +918885558565 +916885123456,,, +91123456987 dsjk `; console.log(`extractValidNumberSequences(test): "${ extractValidNumberSequences(test) }"`);
 .as-console-wrapper { min-height: 100%;important: top; 0; }

const string = 'xtyzjdjgdjf +91888123455, +918885558565 +916885123456, +911234569870' const extractMe = '+91888123455, +918885558565 +916885123456, +911234569870' if (string.includes(extractMe)) { // extractMe is what you want to extract }

最簡單的方法是使用正則表達式: /\+\d*/g 此正則表達式正在搜索所有以+開頭並且之后有 0 個或更多數字的字符串。

 const string = 'xtyzjdjgdjf +91888123455, +918885558565 +916885123456, +911234569870'; const result = [...string.matchAll(/\+\d*/g)] // Get all the regex matches.map(([text]) => text) // Grabbing the first element in the array which is the text.join(','); // Join the text together console.log(result);

資源

var stringVal = "'xtyzjdjgdjf +91888123455, +918885558565 +916885123456, +911234569870".replace('xtyzjdjgdjf','');

控制台.log(stringVal); //打印:+91888123455, +918885558565 +916885123456, +911234569870

對於所有要丟棄的事件,請使用:例如 -- var ret = "data-123".replace(/data-/g,''); PS:replace function 返回一個新的字符串,保持原字符串不變,所以在replace()調用后使用function返回值。

好的,讓我直截了當地說:您要從以“+”符號開頭並以“,”字符結尾的字符串中提取數字序列?

你可以這樣做的方法是遍歷字符串。

let Raw = "udhaiuedh +34242, +132354"

function ExtractNumbers(ToDecode) {
    let StartSet = ["+"]
    let EndSet = [","," "]
    let Cache = ""
    let Finished = []
    
    for (Char of ToDecode) {
        if (StartSet.includes(Char)) {
            if (Cache.length != 0) {
                Finished.push(Cache)
            }
            Cache = ""
        } else if (EndSet.includes(Char)) {
            if (Cache.length != 0) {
                Finished.push(Cache)
            }
            Cache = ""
        } else {
            if (Number(Char)) {
                Cache = Cache + String(Char)
            }
        }
    }
    if (Cache.length != 0) {
        Finished.push(Cache)
    }
    return Finished
}

console.log(ExtractNumbers(Raw))

它並不完美,但是一個很好的例子讓你開始:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM