[英]regular expression Help on - extract a value from a string ignoring the previous contents
can someone help me to write a java regex to retrieve a value from the following string please? 有人可以帮我写一个Java正则表达式来从以下字符串中检索值吗?
XX0001 15NOV XXX SELECTED RAX AXXXXX DXXXXXXXXX REF NBR 002 SSSS
I wanted to extract the value 002. All the strings / characters before 002 are fixed length and properly padded with trailing space (if req.). 我想提取值002。002之前的所有字符串/字符都是固定长度,并用尾随空格正确填充(如果需要)。 could have any string/numeric/special displayable characters.
可以具有任何字符串/数字/特殊的可显示字符。
I am looking for something like ... get 002 from that position ignoring whatever before. 我正在寻找类似...从该位置获取002,而忽略了之前的任何操作。 ?
?
Assuming that you want the last set of digits before the end of the string, you might want to do something like this: 假设您要在字符串末尾之前使用最后一组数字,则可能需要执行以下操作:
^.*\\d{3}\\s+.{4}$
This should instruct the Regex Engine to start matching from the beginning of the string, match any characters and then, from the end, match 3 numbers, a space and any 4 characters. 这应该指示Regex Engine从字符串的开头开始匹配,匹配任何字符,然后从结尾开始匹配3个数字,一个空格和任何4个字符。
Also, if you have fixed sizes and lengths, you can most likely get away with a .substring method, it is less complex. 另外,如果您具有固定的大小和长度,则很可能可以使用.substring方法,因为它不太复杂。
What language? 什么语言?
If javascript: 如果是javascript:
myCode=myString.substring(56,58);
or 要么
myCode=myString.substr(56,3);
If PHP: 如果是PHP:
$myCode=substr($myString,56,3);
This simpler option is preferable to regex because it is faster. 此更简单的选项比regex更可取,因为它速度更快。 You can use this because you're working with fixed length strings.
您可以使用此功能,因为您正在使用固定长度的字符串。
EDIT: Just saw your edit referencing Java. 编辑:刚刚看到您的引用Java的编辑。 So in Java:
因此在Java中:
String myCode = myString.substring(56,59);
You don't need regex to do that. 您不需要正则表达式即可。 Just use the
String
method substring
: 只需使用
String
方法substring
:
String myString = originalString.substring(106,109); // myString = "002"
106 is the begin index, and 109 the end index - 1. To simply get the first, just take the length of the original string just before the number you want to get, for instance: 106是开始索引,109是结束索引-1。要获取第一个索引,只需在要获取的数字之前获取原始字符串的长度即可,例如:
System.out.println("XX0001 15NOV XXX SELECTED RAX AXXXXX DXXXXXXXXX REF NBR ".length());
在Java中
string.substring(56,59);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.