简体   繁体   English

Javascript正则表达式匹配除了双空格然后替换的所有内容

[英]Javascript Regex match everything except double spaces then replace

I need a regex that will match anything except white spaces or only words in between double spaces. 我需要一个正则表达式,它将匹配除空格之外的任何内容或仅在双空格之间的单词。

Like : 喜欢 :

let's assume the underscores where equal to spaces just for example. 让我们假设underscores等于spaces ,例如。

foo_bar__The_Quick_Dog__is_addicted_to___jumping___

Then replace the spaces with any symbol , preferably a Comma (,) . 然后用任何symbol replace spaces ,最好是Comma (,)

So we should have: foo bar, The Quick Dog, is addicted to, jumping. 所以我们应该有: foo bar,The Quick Dog,沉迷于,跳跃。

However, the word jumping should NOT have it's white spaces replaced with comma because it's at the end... adding a comma to it will be meaningless 然而, 跳跃这个词不应该用comma替换它的白色空格,因为它在最后...添加一个comma将是无意义的

I tried: 我试过了:

/\(\s*([^)]+?)\s*\)/

and

[a-z].\s{2,}.*

and

\s\s.*[a-z]

and

(?:[a-zA-Z0-9]+[ ])+[a-zA-Z0-9]+

and a few hundreds more... still no good. 还有几百......还是没有好处。

Thank 谢谢

So you mean like this? 所以你的意思是这样的?

var str = 'foo bar  The Quick Dog  is addicted to  jumping   ';
str.replace(/\s\s+/g, ', ').replace(/, (\n|$)/g, '.$1');
"foo bar, The Quick Dog, is addicted to, jumping."

Replace multi-spaces with "comma space" , then replace "comma space new line" or "comma space end" with "full stop new line" or "full stop end" , respectively. “逗号空格”替换多个空格,然后分别用“全停止新行”“句号结束”替换“逗号空格新行”“逗号空格结束”

Using a replacer ( mdn doc ) : 使用替换器mdn doc ):

var s = 'foo bar  The Quick Dog  is addicted to jumping  ';
s.replace(/ {2,}(.)?/g, function (m, p) { return p ? ', ' + p : '.'; });
// prints "foo bar, The Quick Dog, is addicted to jumping."

Using match + join . 使用match + join This one also trims out the leading whitespaces : 这个也削减了领先的空白:

var s = '   foo bar  The Quick Dog  is addicted to jumping  ';
var m = s.match(/[^ ]+( [^ ]+)*/g);
m && (m.join(', ') + '.'); // null OR join()
// prints "foo bar, The Quick Dog, is addicted to jumping."

match + join inside a function : 在函数内match + join

function fix(str, separator) {
    var m = str.match(/[^ ]+( [^ ]+)*/g);
    return m && (m.join(separator || ', ') + '.');
}

var s = ' ab cd   ef   gh ';
fix(s); // "ab cd, ef, gh."
fix(s, ' - '); // "ab cd - ef - gh."
fix(' '); // null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM