简体   繁体   中英

JavaScript regex to extract different parts of a string

This is an interesting one - I am looking for a JavaScript regex solution to extract different parts from a string. Any input is much appreciated.

Example -

";1XYZ123_UK;1;2.3;evt14=0.0|evt87=0.0,;1XYZ456_UK;4;5.6;evt14=0.0;fly;0;0;;;"

I am trying to extract just these bits from the string ignoring the rest-

“1XYZ123_UK;2;3;1XYZ456_UK;4;5.6;”

Basically extract anything starting with 1XYZ up until it encounters 'evt'.

var s= ";1XYZ123_UK;1;2.3;evt14=0.0|evt87=0.0,;1XYZ456_UK;4;5.6;evt14=0.0"

s = s.replace(/(evt.+?(?:\||;|$))/g, "");

console.log(s) // ";1XYZ123_UK;1;2.3;1XYZ456_UK;4;5.6;"
var s = ';1XYZ123_UK;1;2e.3;evt14=0.0|evt87=0.0,;1XYZ456_UK;4;5.6;evt14=0.0';
var r = s.match(/1XYZ((?!evt).)*/g);

Will give you your desired strings:

["1XYZ123_UK;1;2e.3;", "1XYZ456_UK;4;5.6;"]

Use groups ( (...) ) to capture parts of the matched string. After a successful match the substrings captured can be accessed via the array returned from String.match or Regex.exec .

The first element of the array (index 0) is the whole match, the next (index 1) is the first capture.

Eg.

var re = /1XY(.*)evt/
var result = theString.match(re)

then, if there is a match ( result is not null) then

result[0]

will be the whole match (starting 1XY and ending evt ) while

result[1]

will be the text between those strings.

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