使用正则表达式我想找出字符串的前缀和后缀,如下所示:
T12231 should match ['T', '12231']
Acw2123 should match ['Acw', '2123']
121Ab should match ['121ab', null]
1213 should match [null, '1213']
使用此正则表达式/([0-9]+)$/g
可以轻松匹配字符串末尾的数字。
匹配从字符串开头到此时的所有内容,我无法做到。我得到的最接近的是第一组与/^(.*)([0-9]+)$/g
的最后一个数字相匹配。
答案 0 :(得分:3)
您可以使第一个捕获组变为惰性.*?
,使其匹配尽可能短,即尽可能长地制作第二个捕获组:
var s = ["T12231", "Acw2123", "121Ab", "1213"];
console.log(
s.map(x => x.replace(/^(.*?)([0-9]*)$/, "$1 $2"))
);
将拆分结果推送到数组中:
var s = ["T12231", "Acw2123", "121Ab", "1213"];
var arr = [];
s.forEach(x => x.replace(/^(.*?)([0-9]*)$/, (string, $1, $2) => arr.push([$1, $2])));
console.log(arr);
答案 1 :(得分:1)
你几乎是对的。试试这个:
var re = /^(.*?)(\d+.*)$/g;
var groups = re.exec(your_string)
答案 2 :(得分:1)
满足所有情况
Database account, table account: columns marked: id, login
Database player, table player: columns marked: account_id, name
Database common, table gmlist: columns marked: mAccount, mName
https://regex101.com/r/BWwsIA/1
^(?=\d|.*\d$)((?:(?!\d+$).)*)(\d*)$