[英]java regex capturing 2 numbers
I'm looking for a way to capture the year and the last number of a string.我正在寻找一种方法来捕获字符串的年份和最后一个数字。 ex: "01/02/2017,546.12,24.2," My problem so far I only got Found value : 2017 and Found value : null.
例如:“01/02/2017,546.12,24.2”,到目前为止,我的问题只有 Found value : 2017 和 Found value : null。 I'm not able to capture the group(2).
我无法捕获组(2)。 Thanks
谢谢
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
public class Bourse {
public static void main( String args[] ) {
Scanner clavier = new Scanner(System.in);
// String to be scanned to find the pattern.
String line = clavier.nextLine();
String pattern = "(?<=\\/)(\\d{4})|(\\d+(?:\\.\\d{1,2}))(?=,$)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
} else {
System.out.println("NO MATCH");
}
}
}
Try this one:试试这个:
(\\d{2}\\.?\\d{2})
\\\\d{2}
- exactly two digits \\\\d{2}
- 正好两位数\\\\.?
- optional dot \\\\d{2}
- exactly two digits \\\\d{2}
- 正好两位数If I understood you correctly you're looking for 4 digits, which could be separated by dot.如果我理解正确,您正在寻找 4 位数字,可以用点分隔。
Your requirements are not very clear, but this works for me to simply grab the year and the last decimal value:你的要求不是很清楚,但这对我来说只是简单地获取年份和最后一个十进制值:
Pattern pattern = Pattern.compile("[0-9]{2}/[0-9]{2}/([0-9]{4}),[^,]+,([0-9.]+),");
String text = "01/02/2017,546.12,24.2,";
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
String year = matcher.group(1);
String lastDecimal = matcher.group(2);
System.out.println("Year "+year+"; decimal "+lastDecimal);
}
I don't know whether you're deliberately using lookbehind and lookahead, but I think it's simpler to explicitly specify the full date pattern and consume the value between two explicit comma characters.我不知道您是否故意使用后视和前瞻,但我认为明确指定完整日期模式并使用两个显式逗号字符之间的值更简单。 (Obviously if you need the comma to remain in play you can replace the final comma with a lookahead.)
(显然,如果您需要逗号保持播放状态,您可以用前瞻替换最后一个逗号。)
By the way, I'm not a fan of the \\d
shorthand because in many languages this will match all digit characters from the entire Unicode character space, when usually only matching of ASCII digits 0-9 is desired.顺便说一句,我不喜欢
\\d
速记,因为在许多语言中,这将匹配整个 Unicode 字符空间中的所有数字字符,而通常只需要匹配 ASCII 数字 0-9。 (Java does only match ASCII digits when \\d
is used, but I still think it's a bad habit.) (Java 只在使用
\\d
时匹配 ASCII 数字,但我仍然认为这是一个坏习惯。)
Regex is overkill here.正则表达式在这里有点矫枉过正。
Just split the string on the comma- delimiter .只需在逗号分隔符上拆分字符串即可。
String input = "01/02/2017,546.12,24.2,";
String[] parts = input.split( "," );
Parse each element into a meaningful object rather than treating everything as text.将每个元素解析为一个有意义的对象,而不是将所有内容都视为文本。
For a date-only value, the modern approach uses the java.time.LocalDate
class built into Java 8 and later.对于仅日期值,现代方法使用 Java 8 及更高版本中内置的
java.time.LocalDate
类。
// Parse the first element, a date-only value.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate localDate = null;
String inputDate = parts[ 0 ] ;
try
{
localDate = LocalDate.parse( inputDate , f );
} catch ( DateTimeException e )
{
System.out.println( "ERROR - invalid input for LocalDate: " + parts[ 0 ] );
}
For numbers with decimals where accuracy matters, avoid the floating-point types and instead use BigDecimal
.对于精度很重要的带小数的数字,请避免使用浮点类型,而是使用
BigDecimal
。 Given your class name “Bourse“, I assume the numbers relate to money, so accuracy matters.鉴于您的班级名称“Bourse”,我认为这些数字与金钱有关,因此准确性很重要。 Always use
BigDecimal
for money matters.始终使用
BigDecimal
处理金钱问题。
// Loop the numbers
List < BigDecimal > numbers = new ArrayList <>( parts.length );
for ( int i = 1 ; i < parts.length ; i++ )
{ // Start index at 1, skipping over the first element (the date) at index 0.
String s = parts[ i ];
if ( null == s )
{
continue;
}
if ( s.isEmpty( ) )
{
continue;
}
BigDecimal bigDecimal = new BigDecimal( parts[ i ] );
numbers.add( bigDecimal );
}
Extract your two desired pieces of information: the year, and the last number.提取您想要的两条信息:年份和最后一个数字。
Consider passing around a Year
object in your code rather than a mere integer to represent the year.考虑在您的代码中传递一个
Year
对象,而不仅仅是一个表示年份的整数。 This gives you type-safety and makes your code more self-documenting.这为您提供了类型安全性并使您的代码更具自文档性。
// Goals: (1) Get the year of the date. (2) Get the last number.
Year year = Year.from( localDate ); // Where possible, use an object rather than a mere integer to represent the year.
int y = localDate.getYear( );
BigDecimal lastNumber = numbers.get( numbers.size( ) - 1 ); // Fetch last element from the List.
Dump to console.转储到控制台。
System.out.println("input: " + input );
System.out.println("year.toString(): " + year );
System.out.println("lastNumber.toString(): " + lastNumber );
See this code run live at IdeOne.com .查看此代码在 IdeOne.com 上实时运行。
input: 01/02/2017,546.12,24.2,
输入:01/02/2017,546.12,24.2,
year.toString(): 2017
year.toString(): 2017
lastNumber.toString(): 24.2
lastNumber.toString(): 24.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.