![](/img/trans.png)
[英]Javascript regex - specific number of characters in unordered string
[英]Javascript with Regex to split string at different specific characters
我有以下字符串
Name=(Last, First), Age=(31 year, 6 months, 3 day), Height= 6.1 ft, Employment=None, Email Address =/NA/, Mobile=XXXX
我想將它們拆分為以下內容以構建字典
Name: "(Last, First)"
Age: "(31 year, 6 months, 3 day)"
Height: " 6.1 ft"
...
我遇到了這篇文章並嘗試對其進行調整,但可以使用帶/不帶“()”的鍵使其工作。 這是代碼或來自此鏈接。 感謝您的幫助,並隨時提出更簡單或替代的方法。
txt="Name=(Last, First), Age=(31 year, 6 months, 3 day), Height= 6.1 ft, Employment=None, Email Address =/NA/, Mobile=XXXX" //var r = /.+?=.+?(?=(\([^)]+\),)|(.=)|$)/g; //var r = /.+?=.+?(?=(=(.*),)|$)/g; var r = /.+?=.+?(?=(\),)|(\d\b,)|$)/g; var obj = txt.match(r).reduce(function(obj, match) { var keyValue = match.split("="); obj[keyValue[0].replace(/,\s/g, '')] = keyValue[1]; return obj; }, {}); console.log(obj);
要匹配屬性和值,您可以使用:
(\w+)\s*=\s*(\([^)]+\)|[^,]+)
(\w+)
- 匹配並捕獲屬性(一個或多個單詞字符)\s*=\s*
- 后跟可選空格、a =
和更多可選空格(\([^)]+\)|[^,]+)
- 匹配並捕獲:
\([^)]+\)
- A (
,后跟非)
字符,后跟)
,或[^,]+
- 非逗號字符 const str = 'Name=(Last, First), Age=(31 year, 6 months, 3 day), Height= 6.1 ft, Employment=None, Email Address =/NA/, Mobile=XXXX'; const obj = {}; for (const [, prop, val] of str.matchAll(/(\w+)\s*=\s*(\([^)]+\)|[^,]+)/g)) { obj[prop] = val; } console.log(obj);
如果輸入鍵也可能包含空格,則匹配除 a =
之外的任何內容:
const str = 'Employee Name=(Last, First), Person Age=(31 year, 6 months, 3 day), Height= 6.1 ft, Employment=None, Email Address =/NA/, Mobile=XXXX'; const obj = {}; for (const [, prop, val] of str.matchAll(/(\w[^=]+)\s*=\s*(\([^)]+\)|[^,]+)/g)) { obj[prop] = val; } console.log(obj);
如果您不能使用matchAll
,則使用exec
手動迭代匹配項:
const str = 'Name=(Last, First), Age=(31 year, 6 months, 3 day), Height= 6.1 ft, Employment=None, Email Address =/NA/, Mobile=XXXX'; const obj = {}; const pattern = /(\w+)\s*=\s*(\([^)]+\)|[^,]+)/g; let match; while (match = pattern.exec(str)) { const [, prop, val] = match; obj[prop] = val; } console.log(obj);
這是一種方法,使用智能前瞻僅根據正確的逗號有條件地拆分:
var txt = "Name=(Last, First), Age=(31 year, 6 months, 3 day), Height= 6.1 ft, Employment=None, Email Address =/NA/, Mobile=XXXX" var map = {}; var parts = txt.split(/,\s*(?;[^(]*\))/). parts,forEach(function (item. index) { map[item.split(/=/)[0]] = item;split(/=/)[1]; }). console;log(map);
用於拆分的正則表達式需要解釋:
,\s* match comma with optional whitespace
(?![^(]*\)) assert that we cannot lookahead and see a closing ) without
first seeing an opening (
前瞻條件可防止匹配出現在(...)
項內的逗號。 然后,一旦我們有了術語數組,我們就迭代並構建您想要的字典,將每個術語拆分為=
以找到鍵和值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.