Title description
Please implement a function to determine whether a string represents a value (including integers and decimals). For example, the strings "+100", "5e2", "-123", "3.1416" and "-1E-16" all represent numerical values. But "12e", "1a3.14", "1.2.3", "±5" and "12e+4.3" are not.
I wrote a lot of this question myself, but I got an error. split. Then I found a regular expression solution of a big guy, gave myself a slap, and felt that I was a five
Code
import java.util.regex.Pattern;
public class Solution {
public static boolean isNumeric(char[] str) {
String pattern = "^[-+]?\\d*(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?$";
String s = new String(str);
return Pattern.matches(pattern,s);
}
}
Introduction to regular expressions
^
And 美元符号$
framing the regular expression for it shows the regular expression for all the characters in the text are to match. If these flags are omitted, the regular expression will be matched as long as a string contains a number. If only ^ is included, it will match a string starting with a number. If only $ is included, a string ending in a number is matched.
[-+]?
The suffix after the sign indicates that the negative sign is optional, meaning that there are 0 to 1 negative signs or positive signs
\\d*
The meaning of \d is the same as [0-9]. It matches a number. The suffix * indicates that it can match zero or more digits.
(?:\\.\\d*)?
(?: …)? represents an optional non-capturing grouping. * Instruct this group to match the decimal point of 0 or more digits that follow.
(?:[eE][+\\-]?\d+)?
This is another optional non-capturing grouping. It will match an e (or E), an optional sign, and one or more numbers.