[英]Javascript - Changing string to match regex
I have a text area which I'm getting the value from and want to format this using a regex expression.My regex expression requires a number first space then characters then a multiline break. 我有一个文本区域,我从中获取值,并希望使用正则表达式表达格式。我的正则表达式需要一个数字第一个空格然后字符然后多行中断。
This is my string = "282 MDJSL 889 MSHS 888 MSSH";
(This string could be random each time ). (此字符串每次都可以是随机的)。
So I want to turn this string this so its formated and eventurally put into a JSObject 所以我想把这个字符串转换成这样的字符串,并将其最终放入JSObject中
282 MDJSL
889 MSHS
888 MSSH
This is my current code: 这是我目前的代码:
var textValue = $('#texbox2').val().toString();
var regex = new RegExp('/^[\s\S]*[\d\s]+[a-zA-Z0-9_-]+[\n]+$/');
var str = textValue;
if (regex.test(textValue) === true) {
// Match found
console.log('Regex match');
if ((m = regex.exec(textValue)) !== null) {
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
}
// Match not found
else {
// Not replacing it into the format i want
str = str.replace(regex, str);
}
thanks 谢谢
You could split by whitespace and a positive lookahead of a number. 你可以通过空格和数字的正向前瞻来分割。
var string = "282 MDJSL \\n\\n 889 MSHS 888 MSSH", array = string.split(/\\s+(?=\\d)/); console.log(array);
Seems like you can get by with a simpler regex and code. 看起来你可以使用更简单的正则表达式和代码。
var str = "282 MDJSL 889 MSHS 888 MSSH"; var regex = /\\d+\\s+[az]+/gi; var m; var i = 0; while ((m = regex.exec(str))) { console.log(`Found match, group ${i++}: ${m}`); } if (i === 0) { // was no match }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.