簡體   English   中英

javascript正則表達式以匹配帶數字和不帶數字的字符串

[英]javascript regex to match string with and without number

我不太適合使用正則表達式,花了兩天時間來解決此問題,當然還要在stackoverflow中搜索解決方案,但沒有任何解決方案可以解決我的問題。 這就是問題所在。

使用此代碼,分數變量將增加1

@inc score

我們使用此正則表達式捕獲變量

inc: /^@inc (.*)$/

這是論點

if (match.inc) {
   section = this.addAttribute(match.inc[1] + '+=1', story, section, passage, isFirst, inputFilename, lineCount);
}

然后我嘗試將其提高一點,像這樣

@inc score 15

我改變了正則表達式

inc: /^@inc (.*)( )(.\d*)$/

該代碼可以很好地配合這種更改

if (match.inc) {
   section = this.addAttribute(match.inc[1] + '+=' + match.inc[3], story, section, passage, isFirst, inputFilename, lineCount);
}

我的問題是,正則表達式應該如何? 如果我想兩個都繼續工作

@inc score          <----- will increase by 1

@inc score 100000   <----- will increase by number

當然爭論應該如何?

這是實際的代碼鏈接行197和行299

對不起,我的英語不好,不是我的母語

我將使用此正則表達式^@inc (.*?)(?:(\\s)(\\d+))?$

您可以在這里https://regex101.com/r/dO6yN8/2看到它的運行情況。

在第一個捕獲組中,它捕獲所有內容,直到看到一個空格(如果存在)為止(由於某種原因您希望將該空間放入第二個捕獲組中),然后在第三組中捕獲該空間之后的數字。 但是,空格和數字是可選的。

我不能完全確定您使用的語法(但是,我不太習慣使用JavaScript ...),但是下面的一些代碼片段應該能夠為您提供一些想法:

var scores = ["@inc score", "@inc score 100"];

var re = /@inc score(?: (\d+))?/;

for (i = 0; i < scores.length; i++) {
    var inc = scores[i];

    if (result = inc.match(re)) {
        var addition = "+=" + (result[1] === undefined ? '1' : result[1]);
        alert(addition);
    }
}

jsfiddle演示

當輸入為"@inc score" ,結果變為+=1 ;當輸入為"@inc score 1000" ,結果變為+=1000

(?: (\\d+))? 正則表達式中的匹配包含1個空格和至少1個數字的可選組。 這些數字已被捕獲,並且將在嘗試匹配時成為結果列表的第二個元素。 此元素是條件/三元運算符正在測試的內容。


編輯:糟糕,要使用score作為要增加的變量,您可以使用相同的概念,但結構稍有不同:

var scores = ["@inc score", "@inc score 1000", "@inc amount 1000"];

var re = /@inc (\S+)(?: (\d+))?/;

for (i = 0; i < scores.length; i++) {
    var inc = scores[i];

    if (result = inc.match(re)) {
        var addition = result[1] + "+=" + (result[2] === undefined ? '1' : result[2]);
        alert(addition);
    }
}

我猜在你自己的代碼中,應該像這樣:

inc: /^@inc (\S+)(?: (\d+))?$/

if (match.inc) {
   section = this.addAttribute(match.inc[1] + '+=' + (match.inc[2] === undefined ? '1' : match.inc[2]), story, section, passage, isFirst, inputFilename, lineCount);
}

暫無
暫無

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

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