简体   繁体   English

Javascript正则表达式解析点和空格

[英]Javascript regex parsing dots and whitespaces

In Javascript I have several words separated by either a dot or one ore more whitepaces (or the end of the string). 在Javascript中,我有几个单词由一个点或一个或多个空格(或字符串的结尾)分隔。
I'd like to replace certain parts of it to insert custom information at the appropriate places. 我想替换它的某些部分,以在适当的位置插入自定义信息。

Example: 例:

var x = "test1.test     test2 test3.xyz test4";

If there's a dot it should be replaced with ".X_" 如果有一个点,则应替换为“.X_”
If there's one or more space(s) and the word before does not contain a dot, replace with ".X " 如果有一个或多个空格且前面的单词不包含点,请替换为“.X”

So the desired output for the above example would be: 因此,上述示例的所需输出将是:

"test1.X_test test2.X test3.X_xyz test4.X"

Can I do this in one regex replace? 我可以在一个正则表达式替换中执行此操作吗? If so, how? 如果是这样,怎么样?
If I need two or more what would they be? 如果我需要两个或更多它们会是什么?

Thanks a bunch. 谢谢一堆。

To answer this: 要回答这个问题:

If there's a dot it should be replaced with ".X_" 如果有一个点,则应替换为“.X_”

If there's one or more spaces it should be replaced with ".X" 如果有一个或多个空格,则应替换为“.X”

Do this: 做这个:

x.replace(/\./g, '.X_').replace(/\s+/g, '.X');

Edit: To get your desired output (rather than your rules), you can do this: 编辑:要获得所需的输出(而不是您的规则),您可以执行以下操作:

var words = x.replace(/\s+/g, ' ').split(' ');
for (var i = 0, l = words.length; i < l; i++) {
    if (words[i].indexOf('.') === -1) {
        words[i] += ".X";
    }
    else {
        words[i] = words[i].replace(/\./g, '.X_');
    }
}
x = words.join(' ');

Basically... 基本上...

  1. Strip all multiple spaces and create an array of "words" 剥离所有多个空格并创建一个“单词”数组
  2. Loop through each word. 循环遍历每个单词。
  3. If it doesn't have a period in it, then add ".X" to the end of the word 如果它没有句号,则在单词的末尾添加“.X”
  4. Else, replace the periods with ".X_" 否则,用“.X_”替换句号。
  5. Join the "words" back into a string and separate it by spaces. 将“单词”加入字符串并用空格分隔。

Edit 2 : 编辑2

Here's a solution using only javascript's replace function: 这是一个只使用javascript的替换功能的解决方案:

x.replace(/\s+/g, ' ')  // replace multiple spaces with one space
 .replace(/\./g, '.X_') // replace dots with .X_
 // find words without dots and add a ".X" to the end
 .replace(/(^|\s)([^\s\.]+)($|\s)/g, "$1$2.X$3");

Try this: 尝试这个:

var str = 'test1.test     test2 test3.xyz test4';

str = str.replace(/(\w+)\.(\w+)/g, '$1.X_$2');
str = str.replace(/( |^)(\w+)( |$)/g, '$1$2.X$3');

console.log(str);

In the first replace it replaces the dot in the dotted words with a .X_ , where a dotted word is two words with a dot between them . 在第一次replace它用.X_替换虚线中的点,其中虚线的单词是两个单词,它们之间有一个点

In the second replace it adds .X to words that have no dot, where words that have no dot are words that are preceded by a space OR the start of the string and are followed by a space OR the end of the string . 在第二个replace ,它将.X添加到没有点的单词 ,其中没有点的单词是以空格 开头的单词或字符串的开头,后跟空格字符串的结尾

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

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