如何拆分包含不同符号的字符串? [英] How do I split a string that contains different signs?

查看:147
本文介绍了如何拆分包含不同符号的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想分割一个看起来像这样的字符串:word1; word2; word3,word4,word5,word6.word7。等等。

I want to split a string that can look like this: word1;word2;word3,word4,word5,word6.word7. etc.

字符串来自我从php页面获取的输出,该页面从数据库收集数据,因此字符串可能看起来不同但是第一个单词总是用;然后,最后的单词用。(点)

The string is from an output that I get from a php page that collects data from a database so the string may look different but the first words are always separated with ; and then , and the last words with .(dot)

我希望能够获取以例如结尾的所有单词; , 要么 。成阵列。有人知道怎么做吗?

I want to be able to fetch all the words that ends with for example ; , or . into an array. Does someone know how to do this?

我还想知道如何只获取以...结尾的单词;

I would also like to know how to fetch only the words that ends with ;

下面的函数ends_with(字符串,字符)有效,但它不考虑空格。例如,如果单词是Jonas Sand,它只打印Sand。有谁知道如何解决这个问题?

The function ends_with(string, character) below works but it takes no regard to whitespace. For example if the word is Jonas Sand, it only prints Sand. Anybody knows how to fix this?

推荐答案

可能

var string = "word1;word2;word3,word4,word5,word6.word7";
var array = string.split(/[;,.]/);
// array = ["word1", "word2", "word3", "word4", "word5", "word6", "word7"]

密钥在传递给 String#split 方法的正则表达式中。字符类运算符 [] 允许正则表达式在包含它的字符之间进行选择。

The key is in the regular expression passed to the String#split method. The character class operator [] allows the regular expression to select between the characters contained with it.

如果需要要拆分包含多个字符的字符串,可以使用 | 进行区分。

If you need to split on a string that contains more than one character, you can use the | to differentiate.

var array = string.split(/;|,|./) // same as above

编辑:没有彻底阅读问题。这样的东西

Didn't thoroughly read the question. Something like this

var string = "word1;word2;word3,word4,word5,word6.word7";

function ends_with(string, character) {
  var regexp = new RegExp('\\w+' + character, 'g');
  var matches = string.match(regexp);
  var replacer = new RegExp(character + '$');
  return matches.map(function(ee) {
    return ee.replace(replacer, '');
  });
}
// ends_with(string, ';') => ["word1", "word2"]

这篇关于如何拆分包含不同符号的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆