Sword refers to the "character string representing the value" of the Offer series

Please implement a function to determine whether a string represents a value (including integers and decimals). For example, strings "+100","5e2","-123","3.1416"和"-1E-16","+10.5E-3"all represent numeric values. But "12e","1a3.14","1.2.3","+-5"和"12e+4.3"neither.

It's easy to use regular expressions :

import java.util.regex.Pattern;
public class Solution{
    
    
  	public static boolean isNumeric(char[] str){
    
    
      	String s = new String(str);
      	String pattern = "^[+-]?\\d*(?:\\.\\d*)?(?:[Ee][+-]?\\d+)?$";
    }
}

^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 it only contains ^, it will match a string beginning with a number. If it only contains $, it matches a string ending in a number.

[-+]?

  • The ?suffix after the positive and negative sign indicates that the negative sign is optional, meaning that there are 0 to 1 negative or positive signs

\\d*

  • \\dThe meaning is the same as [0-9]. It matches a number. Suffix *guidelines it matches 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 one e(或E), an optional sign, and one or more numbers.

Guess you like

Origin blog.csdn.net/weixin_44471490/article/details/108969245