[英]js regex extract whitespace between letters. positive lookbehind?
I want to match the \\s
character within any letter, not numbers : 我想匹配任何字母中的
\\s
字符, 而不是数字 :
'abc def ghi'
should match the empty spaces between c
and d
& f
and g
. 应匹配
c
和d
& f
和g
之间的空格。
I think I should use positive lookbehind, but as I know, it`s not posibile in js. 我认为我应该使用积极的外观,但据我所知,它在js中不具备意义。 Any solution?
有解决方案吗
This one should work 这应该工作
(?=[^0-9]+)(\s+)(?=[^0-9]+)
or another tricky way, you just replace your conditional white space by some special text first, eg I use _SPACE_
或者另一种棘手的方法,你只需先用一些特殊的文本替换条件空格,例如我使用
_SPACE_
/([^0-9])(\s+)(?=[^0-9])/$1_SPACE_/
Original text: 原文:
abc defg xhi abc 111 999 111 abc def
After replacing: 更换后:
abc_SPACE_defg_SPACE_xhi_SPACE_abc 111 999 111 abc_SPACE_def
Then you just search for _SPACE_
instead of your conditional white space. 然后,您只需搜索
_SPACE_
而不是条件空格。
Use this code: 使用此代码:
var s = "abc def ghi 3rt"; s = s.replace(/(^|.)(\\s+)(?!\\d)/g, function (m, grp1, grp2, offset, input) { return (grp1.length !== 0 && !((grp1.charCodeAt(0) > 47) && (grp1.charCodeAt(0) < 58))) ? grp1 + "<span>" + grp2 + "</span>" : grp1 + grp2; }); alert(s);
With (^|.)(\\s+)(?!\\d)
, we match any spaces ( \\s+
) that are either at the start of string or after some character that we check for a digit equivalence with (grp1.charCodeAt(0) > 47) && (grp1.charCodeAt(0) < 58)
. 使用
(^|.)(\\s+)(?!\\d)
,我们匹配任何空格( \\s+
),它们位于字符串的开头或者在我们检查数字等价的某个字符之后(grp1.charCodeAt(0) > 47) && (grp1.charCodeAt(0) < 58)
。 And (?!\\d)
makes sure we only match those spaces that are not followed with a digit. 并且
(?!\\d)
确保我们只匹配那些没有跟随数字的空格。
UPDATE UPDATE
If you literally mean to match whitespace between English letters , use 如果你的意思是匹配英文字母之间的空格,请使用
var s = "abc def ghi 3rt"; s = s.replace(/(^|[az])(\\s+)(?=[az])/ig, "$1<span>$2</span>"); document.write(s.replace(/</g,"<").replace(/>/g,">"));
You can use matched group and a lookahead: 您可以使用匹配的组和前瞻:
var s = 'abc def ghi';
var r = s.replace(/([a-z])(\s+)(?=[a-z])/gi, "$1<span>$2</span>");
//=> "abc<span> </span>def<span> </span>ghi"
You can use the split function 您可以使用拆分功能
str = str.replace(" ", "<span> </span>");
and then you can use each function to place in tag :) 然后你可以使用每个函数放在标签:)
text = text.replace(/\s+|(?: )+/g,function(x,i){
if( text.charAt(i-1).match(/[a-zA-Z]/) == null && text.charAt(x.length+i).match(/[a-zA-Z]/) == null ){
return '<span>'+x+'</span>';
} else return x;
});
I`ve changed the rule, that white space should NOT match a-zA-Z 我改变了规则,白色空间不应该与a-zA-Z匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.