【问题标题】:Need a regex to get string separated by underscore [closed]需要一个正则表达式来获取用下划线分隔的字符串[关闭]
【发布时间】:2017-11-26 02:28:35
【问题描述】:

需要一个正则表达式来获取用下划线分隔的字符串

我有字符串one_two_three_four

我需要一个正则表达式从上面的字符串中只获取第二个字符串two

添加了更多信息:

我想要这个正则表达式,因为我有一个 rdbms 表,其中一列中的数据格式为“one_two_three_four”,我只想在获取时从列中获取“两个”。使用以下查询。相反,我再次在 java 中获取数据并拆分数据。

select distinct(REGEXP_SUBSTR(column_name, 'regex'))  
from table_name

【问题讨论】:

  • 只需将其除以_ 并获得第二个元素......这里的正则表达式没有意义
  • 您使用的是什么语言?
  • 你想要这样的东西吗? ^([^_]*_){1}([^_])
  • 啊,剧情变厚了。您还应该标记数据库类型。因为那种数据库函数不是标准的sql,而是有自己的正则表达式风格。
  • 它的Oracle rdbms db

标签: sql regex oracle oracle11g


【解决方案1】:

在 Oracle 中,您确实可以使用 regexp_substr
或者普通的 substr 结合 instr 得到下划线的位置。

例如:

select 
 -- getting the 2nd match with non-underscore characters
 regexp_substr(val, '[^_]+', 1, 2) as method1,

 -- getting the (capture group)
 regexp_substr(val, '^.*?_(.*?)_', 1, 1, null, 1) as method2,

 -- substring on the positions of the underscores
 substr(val,instr(val,'_')+1,instr(val,'_',1,2)-instr(val,'_')-1) as method3

from (
    select 'one_two_three_four' as val from dual
) q

在像 Java 这样的编程语言中?
可以拆分时为什么要使用正则表达式?

String str = "one_two_three_four";

将字符串拆分成数组并取元素1

String[] strArray = str.split("_");
String secondSplit = strArray[1];

或者一口气:

String secondSplit = str.split("_")[1];

顺便说一句,split 也采用正则表达式。 所以这同样有效:

String secondSplit = str.split("[_]")[1];

【讨论】:

  • 如果题外话很快就会被删除,为什么还要回答它?
  • @WiktorStribiżew 因为我认为这会对他有所帮助。查看用户的个人资料,他很有可能正在寻找 Java 解决方案。
  • 当我的代表少于 45,000 时,我的行为曾经是一样的...看到您的声誉下降 30、40、75 分,只是因为您的赞成/接受的答案被删除问题问得不好。
  • 我刚刚添加了更多信息和历史,为什么需要正则表达式。
  • @GouthamNithyananda 为答案添加了 Oracle 解决方案。
猜你喜欢
  • 1970-01-01
  • 2015-11-25
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 2016-08-07
  • 2015-07-19
  • 2014-01-20
相关资源
最近更新 更多