两种替代方法
您的问题的主要挑战是您需要两个单独的项目。这意味着您的流程依赖于另一种语言。 RegEx 本身不解析或分离字符串;它只解释了我们正在寻找的内容。您使用的语言将进行实际分离。我的答案在 PHP 中得到了你的结果,但其他语言应该有类似的解决方案。
如果您只想完成问题中的工作,如果您使用的是 PHP...
方法一:explode("-", $list); -> $array[]
如果您的列表超过两个项目,这很有用:
<?php
// Generate our list
$list = "Common Waxbill - Estrilda astrild";
$item_arr = explode("-", $list);
// Iterate each
foreach($item_arr as $item) {
echo $item.'<br>';
}
// See what we have
echo '
<pre>Access array directly:</pre>'.
'<pre>'.$item_arr[0].'x <--notice the trailing space</pre>'.
'<pre>'.$item_arr[1].' <--notice the preceding space</pre>';
...您可以使用trim() 清理每个项目并将它们重新分配给一个新数组。这将得到您的问题所要求的文本(之前或之后没有额外的空格)......
// Create a workable array
$i=0; // Start our array key counter
foreach($item_arr as $item) {
$clean_arr[$i++] = trim($item);
}
// See what we have
echo '
<pre>Access after cleaning:</pre>'.
'<pre>'.$clean_arr[0].'x <--no space</pre>'.
'<pre>'.$clean_arr[1].' <--no space</pre>';
?>
输出:
Common Waxbill
Estrilda astrild
Access array directly:
Common Waxbill x <--notice the trailing space
Estrilda astrild <--notice the preceding space
Access after cleaning:
Common Waxbillx <--no space
Estrilda astrild <--no space
方法二:substr(strrpos()) & substr(strpos())
如果您的列表只有两个项目,这很有用:
<?php
// Generate our list
$list = "Common Waxbill - Estrilda astrild";
// Start splitting
$first_item = trim(substr($list, strrpos($list, '-') + 1));
$second_item = trim(substr($list, 0, strpos($list, '-')));
// See what we have
echo "<pre>substr():</pre>
<pre>$first_item</pre>
<pre>$second_item</pre>
";
?>
输出:
substr():
Estrilda astrild
Common Waxbill
注意strrpos() 和strpos() 是不同的,每个都有不同的语法。
如果您不使用 PHP,但您想使用其他语言而不依赖于 RegEx,那么了解该语言会很有帮助。
一般来说,编程语言都带有用于此类工作的开箱即用工具,这也是人们选择他们所从事的语言的部分原因。