在Javascript中是否有相当于PHP的preg_match_all?如果没有,那么将正则表达式的所有匹配项放入数组的最佳方法是什么?我愿意使用任何JS库来使它更容易。
答案 0 :(得分:26)
您可以将match
与全局修饰符一起使用:
>>> '1 2 3 4'.match(/\d/g);
["1", "2", "3", "4"]
答案 1 :(得分:10)
John Resig在他的博客上写了一篇名为“Search and dont replace”
的伟大技巧它使用javascript的replace函数,它接受一个回调函数,并且不返回任何内容以保持原始内容不变。
这可能比使用全局匹配并迭代结果数组更简洁,特别是如果你捕获了几个组。
答案 2 :(得分:1)
JS中PHP的preg_match_all更好的等价物是使用exec()函数。这将允许您捕获组,匹配()您不能这样做。
例如,您希望捕获变量myString的所有时间和括号中的数字:
var myString = "10:30 am (15 left)11:00 am (15 left)11:30 am";
var pattern = /(\d{1,2}:\d{1,2}\s?[ap]m)\s\((\d+)/gi;
var match;
while (match = pattern.exec(myString)){
console.log('Match: "' + match[0] + '" first group: -> "' + match[1] + '" second group -> ' + match[2]);
}
输出将是:
Match: "10:30 am (15" first group: -> "10:30 am" second group -> 15
Match: "11:00 am (15" first group: -> "11:00 am" second group -> 15
答案 3 :(得分:0)
elapsed = MainCode()
import random
import string
import multiprocessing
import os
import sys
import time
if __name__ == "__main__":
lines_wanted = input("input how many lines: ") #user can input how many lines he wants
length = input("How long: ") #user can enter how long each line should be
def MainCode(lines_wanted, length):
global elapsed
elapsed = 0.0
starttime = time.time() # start the time
file = open("blablabla.txt", "a",) # open/create the file
i = 0
while 1 == 1:
file.write(''.join(random.choice(string.ascii_letters + string.digits + ".") for i in range(int(length))) + "\n") # write the randomly generated lowercase string
i += 1 * multiprocessing.cpu_count() # count how many lines the loop is on
if i >= int(lines_wanted): # If it reaches the lines it would stop writing
endtime = time.time() # stop the time
elapsed = endtime - starttime #calculate the time
return elapsed
break
processes = []
if __name__ == '__main__':
for _ in range(multiprocessing.cpu_count()):
p = multiprocessing.Process(target=MainCode, args=(lines_wanted, length))
p.start()
processes.append(p)
for process in processes:
process.join()
elapsee = MainCode()
if __name__ == "__main__": # Prints this after finshing the func above
print(f"Finished Writting {lines_wanted} lines, took {elapsee:.1f} to generate")