SC_Adams
SC_Adams

Reputation: 156

RegEx for matching phone numbers with Selenium in HTML tags

NOT an element locator. I need to make sure a phone number (any number) is on the page. If I can find it in a specific element that would be awesome.

<div id="Only456">(555) 555-1212</div>

Upvotes: 0

Views: 467

Answers (1)

Emma
Emma

Reputation: 27743

It may not be the best idea to do so using regular expressions, however if you have /wish to, You can design/modify/change your expressions in regex101.com.

enter image description here

You might want to add any char that you might have in this char list: [0-9-\s()+]

<(.+)>([0-9-\s()+]+)<\/(.+)>

You can also add more boundaries to it, especially instead of using (.+). You can replace them with a list of chars as well such as:

<(.+)>([0-9-\s()+]+)<\/([A-Za-z0-9]+)

RegEx Circuit

You can visualize your expressions in jex.im:

enter image description here

C# Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"<(.+)>([0-9-\s()+]+)<\/(.+)>";
        string substitution = @"$2";
        string input = @"<div id=""Only456"">(555) 555-1212</div>
<h1>+1 800 555-1212</h1>
<span class=""row"">555-555-1212</span>";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
    }
}

JavaScript Demo

const regex = /<(.+)>([0-9-\s()+]+)<\/(.+)>/gm;
const str = `<div id="Only456">(555) 555-1212</div>
<h1>+1 800 555-1212</h1>
<span class="row">555-555-1212</span>`;
const subst = `$2`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Selenium

This post might be helpful.

Upvotes: 1

Related Questions