我有一个文件,这是文件的一部分。所有行中的通用词是PIC,我能够找到PIC的索引。我试图提取每一行的描述。在这里,如何提取单词PIC之前的单词?
15 EXTR-SITE PIC X.
05 EXTR-DBA PIC X.
TE0305* 05 EXTR-BRANCH PIC X(05).
TE0305* 05 EXTR-NUMBER PIC X(06).
TE0305 05 FILLER PIC X(11).
CW0104 10 EXTR-TEXT6 PIC X(67).
CW0104 10 EXTR-TEXT7 PIC X(67).
CW0104* 05 FILLER PIC X(567).
我必须得到如下结果
EXTR-SITE
EXTR-DBA
EXTR-NUMBER
-------
FILLER
我可以使用什么表达方式在“ PIC”之前找到单词吗?
这是我的代码来获取包含“ PIC”的行:
int wordStartIndex = line.indexOf("PIC");
int wordEndIndex = line.indexOf(".");
if ((wordStartIndex > -1) && (wordEndIndex >= wordStartIndex)) {
System.out.println(line); }
最佳答案
您可以尝试这样的正则表达式:
public static void main(String[] args) {
String s = "15 EXTR-SITE PIC X.";
System.out.println(s.replaceAll("(.*?\\s+)+(.*?)(?=\\s+PIC).*", "$1"));
}
O / P:
EXTR-SITE
说明:
(.*?\\s+)+(.*?)(?=\\s+PIC).*", "$1") :
(.*?\\s+)+ --> Find one or more groups of "anything" which is followed by a space.
(.*?)(?=\\s+PIC) -->find a group of "any set of characters" which are followed by a space and the word "PIC".
.* --> Select everything after PIC.
$1 --> the contents of the actual String with the first captured group i.e, data between `()`.
PS:这适用于您当前的所有输入:P
关于java - 根据下一个单词在一行中找到一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28893140/