简体   繁体   English

正则表达式组Java

[英]Regular expressions Groups java

Hi I am writing regular expression:I need get info from this line 嗨,我正在写正则表达式:我需要从这一行获取信息

;row:1;field:2;name:3

My regular expression for this line is 我对此行的正则表达式是

.*(row:([0-9]{1,}))?;.*field:([0-9]{1,});.*name:([0-9]{1,});

But the problem that the word row is optional,I can also get the line without word row,but in this case my regular expressions does not work,how I can write it? 但是单词行是可选的问题,我也可以得到没有单词行的行,但是在这种情况下我的正则表达式不起作用,我怎么写呢?

Thanks. 谢谢。

If you are just trying to make the word row optional, you can surround it with parenthesis and use the question mark to say you want zero or one of the parenthesis contents. 如果您只是想使单词行可选,则可以用括号将其括起来,并使用问号表示您希望零个或一个括号内容。 I have shown below: 我已经显示如下:

(row:)?

This will find zero or one of "row:". 这将找到零或“行:”之一。 I would recommend also adding the ?: operator inside the open parenthesis if you are not trying to creating match groups: 如果您不尝试创建匹配组,我还建议在圆括号内添加?:运算符:

(?:row:)?

Adding the ?: operator tells the program that the parenthesis is not part of a match group, and you are using the parenthesis just to group the letters. 添加?:运算符将告诉程序括号不是匹配组的一部分,而您使用括号只是将字母分组。 So putting this into your regular expression looks like this: 因此,将其放入正则表达式中看起来像这样:

.*((?:row:)?([0-9]{1,}))?;.*field:([0-9]{1,});.*name:([0-9]{1,});

If you want this applied to "field:" and "name:", then you would get this: 如果要将其应用于“ field:”和“ name:”,则将得到以下信息:

.*((?:row:)?([0-9]{1,}))?;.*(?:field:)?([0-9]{1,});.*(?:name:)?([0-9]{1,});

If you do not want the other parenthesis in your expression to create match groups, I would also change them. 如果您不希望表达式中的另一个括号创建匹配组,我也将对其进行更改。 Also, to shorten the expression a little and make it cleaner I would change [0-9] to \\d which means any digit, and I would replace {1,} with + which means "one or more", and remove the unnecessary parens which results in this: 另外,为了稍微缩短表达式并使它更整洁,我将[0-9]更改为\\d表示任何数字,并将{1,}替换为+表示“一个或多个”,并删除了不必要的内容导致以下结果:

.*(?:(?:row:)?\\d+)?;.*(?:field:)?\\d+;.*(?:name:)?\\d+;

I'm not really sure that this is the final expression that you want, since your question was not very descriptive, but I have shown you how to find one or more of "row:" and clean up the expression a little without changing its meaning. 我不太确定这是您想要的最终表达式,因为您的问题不是很具描述性,但是我已经向您展示了如何找到一个或多个“ row:”并在不更改表达式的情况下对其进行了一些清理含义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM