簡體   English   中英

正則表達式:如何匹配非ASCII字符串的所有大寫字符

[英]Regex: How to match all uppercase characters of non-ascii string

我有像Japan CompanyChinese Company和這個正則表達式/([AZ])/g這樣的字符串來獲取所有大寫字符,然后加入結果以發出它們。 但是當輸入字符串不是英文字母時,正則表達式不起作用。

let string = "Japan Company";
console.log(string.match(/[A-Z]/g).join('')); // JC

但是當我有一個像日本の會社這樣的字符串時

let string = "日本の會社";
console.log(string.match(/[A-Z]/g).join(''));

這會引發異常,因為string.match(/[AZ]/g)的結果是null

當我試圖省略這些字符串並且象形文字沒有大寫時,正則表達式應該只匹配每個單詞的第一個字符,其中單詞用空格分隔。

我應該為此使用什么通用正則表達式?

類似於 POSIX 的[:upper:] ,但這不適用於 JavaScript 正則表達式引擎。

您可以使用

(string.match(/(?<!\S)\S/g) || [string]).join('')

請參閱 JavaScript 演示:

 const strings = ["Japan Company", "japan company", "日本の會社"]; for (const string of strings) { console.log(string, '=>', (string.match(/(?<!\S)\S/g) || [string]).join('').toUpperCase()) }

(?<!\S)\S正則表達式匹配字符串開頭或空白字符之后的非空白字符。

Safari,非后視模式:

 var strings = ["Japan Company", "japan company", "日本の會社"]; for (var i=0; i<strings.length; i++) { var m = strings[i].match(/(?:^|\s)(\S)/g) if (m === null) { console.log(strings[i], '=> ', strings[i]) } else { console.log(strings[i], '=>', m.join('').replace(/\s+/g, '').toUpperCase()) } }

根據您的評論,我認為這應該做您想要的。

function getUppercaseLetters(string) {
    // Find uppercase letters in the string
    let matches = string.match(/[A-Z]/g);
    // If there are no uppercase letters, get the first letter of each word
    if (!matches) matches = string.split(" ").map(word => word[0]);
    // If there are still no matches, return an empty string. This should prevent against any edge cases.
    if (!matches) return "";
    // Join the array elements and make it uppercase.
    return matches.join("").toUpperCase();
}

暫無
暫無

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

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