如何使用空格分隔符获取任何通用单词或句子中的第 n 个字符串 [英] How to get the nth string in any generic word or sentence with a space delimiter

查看:46
本文介绍了如何使用空格分隔符获取任何通用单词或句子中的第 n 个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取句子中的第 n 个单词或一组带有空格分隔符的字符串?

How do I get the nth word in a sentence or a set of strings with space delimiter?

很抱歉更改了要求.谢谢.

Sorry for the change in the requirement.Thank you.

推荐答案

通过使用 instr.

select substr(help, 1, instr(help,' ') - 1)
  from ( select 'hello my name is...' as help
           from dual )

instr(help,' ') 返回第二个参数在第一个参数中第一次出现的位置索引,包括您要搜索的字符串.即第一次出现 ' ' 在字符串 'hello my name is...' 加上空格.

instr(help,' ') returns the positional index of the first occurrence of the second argument in the first, inclusive of the string you're searching for. i.e. the first occurrence of ' ' in the string 'hello my name is...' plus the space.

substr(help, 1, instr(help,' ') - 1) 然后将输入字符串从第一个字符到 instr(....然后我删除了一个,以便不包含空格..

substr(help, 1, instr(help,' ') - 1) then takes the input string from the first character to the index indicated in instr(.... I then remove one so that the space isn't included..

对于第 n 次,只需稍微改变一下:

For the nth occurrence just change this slightly:

instr(help,' ',1,n)' ' 从第一个字符开始出现的 n 次.然后你需要找到下一个索引的位置索引instr(help,' ',1,n + 1),最后找出它们之间的差异,这样你就知道你的substr(....当您在寻找 n 时,当 n 为 1 时,这会崩溃,您必须处理它,像这样:

instr(help,' ',1,n) is the nth occurrence of ' ' from the first character. You then need to find the positional index of the next index instr(help,' ',1,n + 1), lastly work out the difference between them so you know how far to go in your substr(.... As you're looking for the nth, when n is 1 this breaks down and you have to deal with it, like so:

select substr( help
             , decode( n
                     , 1, 1
                     , instr(help, ' ', 1, n - 1) + 1
                       )
             , decode( &1
                     , 1, instr(help, ' ', 1, n ) - 1
                     , instr(help, ' ', 1, n) - instr(help, ' ', 1, n - 1) - 1
                       )
               )
  from ( select 'hello my name is...' as help
           from dual )

这也会在 n 处崩溃.正如您所看到的,这变得很荒谬,因此您可能需要考虑使用 正则表达式

This will also break down at n. As you can see this is getting ridiculous so you might want to consider using regular expressions

select regexp_substr(help, '[^[:space:]]+', 1, n )
  from ( select 'hello my name is...' as help
           from dual )

这篇关于如何使用空格分隔符获取任何通用单词或句子中的第 n 个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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