About Regular Expressions

Asked 1 years ago, Updated 1 years ago, 55 views

  li id="result_0" data-hoge="4592105095" class="s-result-item"
4592105095

I want answer like this
Thank you for your cooperation.

regular-expression

2022-09-30 17:01

3 Answers

Since there was no language specification, we will respond using JavaScript (the expressions in other languages are different, which is the same way of thinking).

var regexp=newRegExp('data-hoge="(.*?)");
var result=regexp.exec('li id="result_0" data-hoge="4592105095" class="s-result-item");
alert(result[1]);

Use ( ) to retrieve the matching value.The values enclosed by ( ) are the number of ( ) and the result array is entered from 1 to 1.This time, there is only one, so it is in index 1.

You must also use the shortest regular expression match.That's why I'm adding the ? of (.*?).Without ?, the result is 4592105095" class="s-result-item.This is because it matches up to the last ""."""Use ? to match the expression as soon as possible.


2022-09-30 17:01

Is it a replacement using regular expressions?
Search string data-hoge="(.*?)"
Replace string$1
But if you simply want to hit a number, it's like (?<=data-hoge=").*?(?=").


2022-09-30 17:01

How to use DOM in PHP

<?php
$src='liid="result_0" data-hoge="4592105095" class="s-result-item";
$dom = new DOMDocument();
$dom->loadHTML("<html><body><".$src."/>/body></html>");#Not strict w
$answer=$dom->getElementById('result_0')->getAttribute('data-hoge');
echo$answer;
?>


2022-09-30 17:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.