簡體   English   中英

有人可以建議使用單行正則表達式來解析帶有 - 或 / 分隔符的字母數字和可選數字 ID 嗎?

[英]Can someone suggest a one-line regex to parse out alphanumeric and optional numeric ids with either a - or / separator?

我正在嘗試解析一組遵循以下模式的字符串

{alpha-numeric-id}-{numeric-id}

或者

{alpha-numeric-id}/{numeric-id}
  1. alpha-numeric-id可以包括-字符和數字
  2. numeric-id始終是一個數字,並且是可選的。
  3. alpha-numeric-idnumeric-id可以用-/分隔

我想在一個步驟中解析出alpha-numeric-idnumeric-id (如果有的話)。

例子

'ThePixies1996' => { 1: 'ThePixies1996', 2: '' }
'7ThePixies' => { 1: '7ThePixies', 2: '' }
'The-Pixies' => { 1: 'The-Pixies', 2: '' }
'The-Pixies-1234567' => { 1: 'The-Pixies', 2: '1234567' }
'The-Pixies/1234567' => { 1: 'The-Pixies', 2: '1234567' }

到目前為止,我想出的最簡單的方法如下:

const parse = str => {
  const numeric = str.match(/[-\/]([0-9]+)/)

  return numeric
    ? {
      numericId: numeric[1],
      alphaNumericId: str.slice(0, -1 * (numeric[1].length + 1))
    }
    : {
      numericId: '',
      alphaNumericId: str
    }
}

有沒有更簡單的方法?

如果您知道要做什么,正則表達式會簡單得多。 話雖如此,這將是一個理想的解決方案:

^([\da-z-]+?)(?:[-/](\d+))?$

解釋:

  • ^匹配字符串開頭
  • ([\\da-z-]+?)匹配並捕獲包含- (非貪婪)的字母數字字符串
  • (?:[-/](\\d+))? 匹配以字符開頭的字符串-/跟在一系列數字(被捕獲)之后(可選)
  • $字符串結尾

觀看現場演示

JS代碼:

 var matches = []; 'The-Pixies/12345'.replace(/^([\\da-z-]+?)(?:[-/](\\d+))?$/ig, function(m, $1, $2) { matches.push($1, $2); }) console.log(matches.filter(Boolean));

您可以使用

(.+?)(?:[\/-](\d+))?$

https://regex101.com/r/PQSmaA/1/

通過延遲重復任何字符來捕獲組中的alphaNumericId ,然后可以選擇有一組破折號或正斜杠,后跟在另一組中捕獲的數字numericId 解構匹配並為 numericId 分配一個默認值(空字符串)以快速返回所需的對象:

 const input = ['ThePixies1996', '7ThePixies', 'The-Pixies', 'The-Pixies-1234567', 'The-Pixies/1234567' ]; function parse(str) { const [_, alphaNumericId, numericId = ''] = str.match(/(.+?)(?:[\\/-](\\d+))?$/); return { alphaNumericId, numericId }; } console.log( input.map(parse) );

那是假設輸入總是有效的,就像你的parse函數一樣。 如果不是,並且您還需要測試輸入是否為所需格式,請使用字符集而不是. , 並在所需格式不匹配時拋出或其他內容:

 const input = ['ThePixies1996', '7ThePixies', 'The-Pixies', 'The-Pixies-1234567', 'The-Pixies/1234567', 'invalid/input/string' ]; function parse(str) { const match = str.match(/^([az\\d-]+?)(?:[\\/-](\\d+))?$/i); if (!match) return 'INVALID'; const [_, alphaNumericId, numericId = ''] = match; return { alphaNumericId, numericId }; } console.log( input.map(parse) );

您可以以更簡單的方式在沒有正則表達式的情況下完成

const parse = (data) => {
    let inx = data.lastIndexOf("-")
    if (inx === -1 || isNaN(data.slice(inx))){
        inx = data.lastIndexOf("/")  
    }
    return {
          numericId: data.slice(0, inx),
          alphaNumericId: data.slice(inx+1)
    }
}

暫無
暫無

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

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