简体   繁体   中英

regular expression to match data

I have array of items like below

[1;233,2;345,3;656]

am looking for regular expression to save my array like below

[233,345,656]

so which discards value before semi colon

perhaps try regex replace on [0-9]+; with an empty string. If there is only going to be a single digit then the + is not needed. In the case of a single digit it may also be easier to just find a semicolon, delete it and the preceding character.

replaceAll("\d;" ,"")

如果数字位数不固定为1,并且可以更改,则可以使用\\d+

That'd be something like:

;([^,;]+)$1

That means at least one semicolon as a starting character, then one or more characters that are neither a semicolon nor a comma. Finally, it marks only the part to the right of the semicolon as the desired result.

I'm not sure this is the syntax for Java, specifically. I'm more of a .NET guy. But you can work your way from there.

You can split your array string by , to get the couples and than by ; to find the numbers.

PHP:

$string= "[1;233,2;345,3;656]";
$temp=explode(",", $string); //to get couples like 1;233
print_r($temp);
$result=array();
for($i=0; $i<count($temp);$i++){
    $temp1=explode(";", $temp[$i]);
    array_push($result,$temp1[1] );//take second value 233
}
print_r($result);

Output: $couple_array: Array ( [0] => [1;233 [1] => 2;345 [2] => 3;656] )

Output: $array: Array ( [0] => 233 [1] => 345 [2] => 656] )

Java:

String str = "[1;233,2;345,3;656]";
String[] temp = str.split(",");//to get couples like 1;233
int size=temp.length;
String[] result=new String[size];
for(int i =0; i < size ; i++){
    String[] temp1=str.split(";");//take second value 233
    result[i]=temp1[1];
}

If your array is typed with integers, regular expressions are out of scope. You should consider creating a new array with integers of value superior to, say, 99 (3-digit integers).

However, if your array contains Strings, here's the regex you want:

Pattern yourPattern = Pattern.compile("(?<=\\D)\\d{1,2}(?=\\D)"); 
// this will find 1 or 2 digit numbers preceded and followed by anything but a digit

Edit : for the regular expressions solution, I assume we are talking about the String representation of an Array. Hence the check for non-numerical characters. If instead you were iterating over an array of String, then you could probably use Integer.valueOf("12") and compare if to int value 99. That is, if you're positive your Strings will always represent an Integer (or handle a NumberFormatException otherwise).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM