简体   繁体   English

用两个字符分隔字符串

[英]Split a string by two characters

Firstable i want to match if a string has the following format: $abc #xyz or $abc .xyz . 首先,如果字符串具有以下格式,我想进行匹配: $abc #xyz$abc .xyz

The abc and xyz mean only alphanumeric string. abcxyz仅表示字母数字字符串。

If it's matched then i need to extract the first $abc and the last #xyz , all that using pure javascript and maybe regex. 如果匹配,那么我需要提取第一个$abc和最后一个#xyz ,所有这些都使用纯JavaScript以及正则表达式。

The pattern is in the following order: 模式按以下顺序:

  1. Dollar Sign 美元符号
  2. Unlimited alphanumeric string 无限的字母数字字符串
  3. space 空间
  4. a hash or point 哈希或点
  5. Unlimited alphanumeric string 无限的字母数字字符串

Thanks in advance for any help. 在此先感谢您的帮助。

Try the following regular expression: 尝试以下正则表达式:

/^(\$[a-zA-Z\d]+) ([#.][a-zA-Z\d]+)$/

Explanation: 说明:

^              Start of line.
(              Start capturing group.
\$             Literal dollar sign.
[a-zA-Z\d]     Any letter in a-z or A-Z, or any digit.
+              One or more of the previous.
)              End capturing group.
<space>        Literal space.
(              Start second capturing group.
[#.]           Either a number sign or a period.
[a-zA-Z\d]+ 
)              End second capturing group.
$              End of line.

Example usage: 用法示例:

> var s = '$abc #xyz';
> s.match(/^(\$[a-zA-Z\d]+) ([#.][a-zA-Z\d]+)$/);
["$abc #xyz", "$abc", "#xyz"]

Like this? 像这样?

if(str.match(/^\$[a-z0-9]+ (#|\.)[a-z0-9]+$/i)) {
    var parts = str.split(' ');
}

Update: Obviously there a various ways to achieve this. 更新:显然有多种方法可以实现此目的。 There is not the one regular expression. 没有一个正则表达式。 If you make use of capture groups, you can extract the strings even in one step ( like Mark showed in his answer ). 如果您使用捕获组,则即使一步也可以提取字符串( 如Mark在其答案中所示 )。

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

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