我有一个这种格式的字符串
FUTSTKACC28-APR-2016
ACC是一个符号,28-APR-2016是一个到期日 FUTSTK是预定义词
如何在这种情况下检索值符号和日期
例如如何获得 ACC
和
28-APR-2016
一些示例数据
FUTSTKACC26-MAY-2016
FUTSTKACC28-APR-2016
FUTSTKACC30-JUN-2016
FUTSTKADANIENT26-MAY-2016
FUTSTKADANIENT28-APR-2016
FUTSTKADANIENT30-JUN-2016
答案 0 :(得分:5)
您有固定长度的前缀字和固定长度的日期。您可以删除前缀,然后使用日期中的11个字符从右侧获取子字符串。像,
String[] sample = { "FUTSTKACC26-MAY-2016", "FUTSTKACC28-APR-2016",
"FUTSTKACC30-JUN-2016", "FUTSTKADANIENT26-MAY-2016",
"FUTSTKADANIENT28-APR-2016", "FUTSTKADANIENT30-JUN-2016" };
String predefWord = "FUTSTK";
for (String input : sample) {
if (input.startsWith(predefWord)) {
input = input.substring(predefWord.length());
// There are 11 characters in the date format
String symbol = input.substring(0, input.length() - 11);
String dateStr = input.substring(input.length() - 11);
System.out.printf("symbol=%s, date=%s%n", symbol, dateStr);
}
}
输出
symbol=ACC, date=26-MAY-2016
symbol=ACC, date=28-APR-2016
symbol=ACC, date=30-JUN-2016
symbol=ADANIENT, date=26-MAY-2016
symbol=ADANIENT, date=28-APR-2016
symbol=ADANIENT, date=30-JUN-2016
答案 1 :(得分:3)
这样的事情应该有效:
final String PATTERN = "(FUTSTK)(.+)(\d\d-\w\w\w-\d\d\d\d)"
Pattern p = Pattern.compile(PATTERN);
Matcher m = p.matcher("FUTSTKACC28-APR-2016");
String symbol = m.group(1);
DateFormat format = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
Date date = format.parse(string);
答案 2 :(得分:0)
正则表达式方法(从@ElliottFrisch窃取的位)假设您知道预定义的单词:
String[] sample = { "FUTSTKACC26-MAY-2016", "FUTSTKACC28-APR-2016",
"FUTSTKACC30-JUN-2016", "FUTSTKADANIENT26-MAY-2016",
"FUTSTKADANIENT28-APR-2016", "FUTSTKADANIENT30-JUN-2016" };
String predefined = "FUTSTK";
Pattern p = Pattern.compile(Pattern.quote(predefined) + "(\\w+)(\\d\\d-\\w\\w\\w-\\d\\d\\d\\d)");
for (String s: sample) {
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(m.group(1) + " " + m.group(2));
}
}
输出:
ACC 26-MAY-2016
ACC 28-APR-2016
ACC 30-JUN-2016
ADANIENT 26-MAY-2016
ADANIENT 28-APR-2016
ADANIENT 30-JUN-2016
答案 3 :(得分:0)
final String str = "FUTSTKACCCCCCC28-APR-2016";
final String[] strArr = str.split("-");
final String month = strArr[0].substring(strArr[0].length() - 2);
final String word = strArr[0].substring(0, strArr[0].length() - 2);
System.out.println("word: " + word);
System.out.println("date: " + month + "-" + strArr[1] + "-" + strArr[2]);