使用可选值改进正则表达式。

时间:2022-12-19 03:58:25

(Working with Regex in C#)

(在c#中与Regex合作)

I've several regular expresions to parse a line in several fields. One of this fields have an optional char that I can't figure how to make my regex to split it. I tried to improve it in one line but I couldn't do it.

我有几个常规执行程序来解析几个字段中的一行。其中一个字段有一个可选的字符,我不知道如何使regex将其拆分。我试着用一行来改进它,但我做不到。

My input:

我的输入:

4-002 TERMO CONTINENTAL 1 L N°3995 9.22 4-003 TERMO CONTINENTAL 2 N°3996 99.22

My desidered output:

我desidered输出:

Item[0].Code = 4-002
Item[0].Detail = TERMO CONTINENTAL 1 L N°3995
Item[0].Price = 9.22

Item[1].Code = 4-003
Item[1].Detail = TERMO CONTINENTAL 2 N°3996
Item[1].Price = 99.22

My last attempt:

我最后一次尝试:

To separete both items: (?=\d\-\d\d\d\s.*)
This is not working because some codes are: like 14-001 instead 4-001
I tried with: ([\d]\d\-\d\d\d\s.*) but neither works

为了区分这两个项目:(?=\d\ d\d\d\ d\s.*)这是无效的,因为有些代码是:14-001而不是4-001

QUESTION: How can I retrieve both possibilities? 14-001 and 4-001

问:我怎样才能找回这两种可能性?14 - 001和4 - 001

And in the other things are related to this problem:
To separate detail from price: ([^\s]*$) (from one item splitted before)
To separate code from detail: (\d\-\d\d\d\s) (same problem as original question)

和这个问题相关的其他东西:从价格:单独的细节(^ \[s]* $)(从一项分裂之前)将代码从细节:(\ d \ \ d \ d \ d \ s)(同样的问题最初的问题)

Any help with this regular expression will be helpful and valorated.

任何关于这个正则表达式的帮助都将是有益的和有价值的。

Thanks in advance!

提前谢谢!

2 个解决方案

#1


2  

I believe the following regex is safe to use:

我相信以下regex是安全的:

(\d+-\d+)\s+(.*?N°\d+)\s+(\d+\.\d+)

See regex demo

查看演示正则表达式

If the Item.Detail can have any text and it is located between a digits-digits and a float value, use

如果项目。细节可以有任何文本,它位于数字和浮点值之间

(\d+-\d+)\s+(.*?)\s+(\d+\.\d+)

See another demo

看到另一个演示

Results:

结果:

使用可选值改进正则表达式。

See IDEONE demo

看到IDEONE演示

#2


1  

Try

试一试

(\d+-\d\d\d)(.*?)(\d+\.\d\d)

The + is for one or more occurrences.

+代表一个或多个事件。

#1


2  

I believe the following regex is safe to use:

我相信以下regex是安全的:

(\d+-\d+)\s+(.*?N°\d+)\s+(\d+\.\d+)

See regex demo

查看演示正则表达式

If the Item.Detail can have any text and it is located between a digits-digits and a float value, use

如果项目。细节可以有任何文本,它位于数字和浮点值之间

(\d+-\d+)\s+(.*?)\s+(\d+\.\d+)

See another demo

看到另一个演示

Results:

结果:

使用可选值改进正则表达式。

See IDEONE demo

看到IDEONE演示

#2


1  

Try

试一试

(\d+-\d\d\d)(.*?)(\d+\.\d\d)

The + is for one or more occurrences.

+代表一个或多个事件。