正则表达式-单词后不要匹配空值 [英] Regex - Don't match nulls after words

查看:239
本文介绍了正则表达式-单词后不要匹配空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在管道(|)上分割了一个字符串,当缺少字段时,正则表达式[^|]*正常工作,但是它在单词后匹配空字符:

I'm splitting a string on pipes (|) and the regex [^|]* is working fine when there are missing fields, but it's matching null characters after words:

GARBAGE|||GA|30604 产生匹配项

GARBAGE, null, null, null, GA, null, 30604, null

我也尝试过[^|]+会产生匹配结果

I've also tried [^|]+ which yields matches

GARBAGE, GA, 30604

我想要的是GARBAGE, null, null, GA, 30604.而||||将产生匹配项null, null, null, null, null.

What I want is GARBAGE, null, null, GA, 30604. And |||| would yield matches null, null, null, null, null.

我要按索引引用匹配项,那么如何修复正则表达式,使其按字段匹配,如果该字段中没有其他数据,则包括null?

I'm referencing matches by index, so how can I fix the regex so it matches field by field, including nulls if there is no other data in the field?

推荐答案

这是split的工作方式.您应该使用拆分类型函数.
总是有 bias 拆分用法.

This is how split works. You should use a split type function.
There is always a bias split uses.

您的情况很简单,因为它会分割为一个字符,通常情况下不需要正则表达式.
并且在这种情况下,使用正则表达式,如果不先行/不先行,就无法实现偏差.

Your case is simple in that it splits on a single character, in normal cases a regex is not needed.
And in this case, using a regex, the bias cannot be achieved without lookahead/lookbehind.

 # (?:^|(?<=\|))([^|]*)(?=\||$)

 (?:
      ^                     # BOS
   |                      # or
      (?<= \| )             # Pipe behind
 )
 ( [^|]* )             # (1), Optional non-pipe chars
 (?=
      \|                    # Pipe ahead
   |                      # or
      $                     #  EOS
 )

这篇关于正则表达式-单词后不要匹配空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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