So i am using javascript and i need to use regex to match some data with a mix of numbers and letters, but since i am learning regex at the moment this task is too complicated for me to understand and make it work like i want it, any ideas ?
[ABC][122/29] [13:40] [RANDOM_TEXT] [PRT] [TPT] [RANDOM] [ 1113B86JD ] RANDOM [ABC][122/29] [13:40] [RANDOM_TEXT] [PRT] [TPT] [RANDOM] [ 115M3X2G9 ] RANDOM [ABC][122/29] [13:40] [RANDOM_TEXT] [PRT] [TPT] [RANDOM] [ 1113P86JD ] RANDOM [ABC][122/29] [13:40] [RANDOM_TEXT] [PRT] [TPT] [RANDOM] [ 314PTVPNL ] RANDOM [ABC][122/29] [13:40] [RANDOM_TEXT] [PRT] [TPT] [RANDOM] 114PAVPNL RANDOM
90% of the time the data i want is between two brackets length grater then 5 characters, so i found two regex's, And the rest of the data is still mix of numbers and letters but without the brackets.
[(.*?)]
For getting the data between brackets
^([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*$
For getting the mix of numbers and letters
Now how to i combine both, i tried a bunch of times to make it work but it didnt work, can someone help me with this.
The pattern you seem to be after is any combination of 9 letters and numbers (no more, no less). I also think you want is to have the search continue after the first match. If so, you use the global flag g
. See Snippet for details.
SNIPPET
var str = '[ABC][122/29] [13:40] [RANDOM_TEXT] [PRT] [TPT] [RANDOM] [1113B86JD] RANDOM [ABC][122/29] [13:40] [RANDOM_TEXT] [PRT] [TPT] [RANDOM] [115M3X2G9] RANDOM [ABC][122/29] [13:40] [RANDOM_TEXT] [PRT] [TPT] [RANDOM] [1113P86JD] RANDOM [ABC][122/29] [13:40] [RANDOM_TEXT] [PRT] [TPT] [RANDOM] [314PTVPNL] RANDOM [ABC][122/29] [13:40] [RANDOM_TEXT] [PRT] [TPT] [RANDOM] 114PAVPNL RANDOM'; var res = str.match(/(\\b\\w{9}\\b)/g); /* \\b word boundry || \\w Any word or number || {9} 9 of \\w || \\b word boundry */ console.log(res);
You need to enclose your letters-and-digits regex (ie the second one without ^
and $
anchors) with special "compound brackets":
(?:^|\[|\s)((?:[0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*)(?:$|\]|\s)
The opening "compound bracket" may be represented by start of text ( ^
), an opening square bracket ( \\[
) or a space ( \\s
). Hence the (?:^|\\[|\\s)
at the start of the regex.
The closing "compound bracket" may be represented by end of text ( $
), a closing square bracket ( \\]
) or a space ( \\s
). Hence the (?:$|\\]|\\s)
at the end of the regex.
The letter and digit sequence you need is in the first capture group.
Demo: https://regex101.com/r/WLwu9p/1
Please note I made the group ( (...)
) from your second expression non-capturing ( (?:...)
) since in this particular case only grouping is required.
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.