daily-share icon indicating copy to clipboard operation
daily-share copied to clipboard

正则学习(2021-06-22)

Open yaogengzhu opened this issue 3 years ago • 11 comments

/**
 * 匹配16进制
 * 
 * #ffbbad
 * #Fc01DF
 * #FFF
 * #ffE
 */
const regx = /#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})/g
const string = "#ffbbad #Fc01DF #FFF #ffE";
const res = string.match(regx)
console.log(res)

/**
 *  匹配时间
 *  01:59
 *  23:59
 *  
 */
const rgex1 = /(([0][1-9])|([2][0-3]))[:]([0-5][0-9])/g // x
/**
 *  1. 必须以什么开头
 *  2. 必须以什么结尾
 *  3. 分支结构不需要每一个都是用()包裹,利用 | 即可
 *  4. 普通符号,不需要[]进行包
 */
// const regx1 = /^([01][0-9]|[2][0-3]):[0-5][0-9]$/
const regx2 = /^([01][0-9]|[2][0-3]):[0-5][0-9]$/
regx2.test("23:59") 

/**
 *  匹配手机号
 *  1[3,5,7,8]********
 */
const regx3 = /^[1][3578][0-9]{9}$/

/**
 * 匹配邮箱 
 * [email protected]
 * [email protected]
 * [email protected]
 * 
 * 操作思路
 * 1.以\w 单词数字符号开头, 
 * 2.+ 匹配至少出现一次
 * 3.@ 匹配@符号
 * 4.[.]小数点需要[]包裹
 * 5 {m, } 至少出现m次
 */
const regx4 = /^\w+@\w+[.][a-zA-Z]{2,}$/


/**
 * ‘(112)(()22(  )(())qqq()’
 * 
 * 匹配() ()
 * 
 * 操作思路
 * 1. 匹配() \( 英文符号需要转义 
 * 2. 符号( 中间可能有多个空格 \s*
 * 3. 也有可能有(中文括号,需要采用多选分支处理, 中文符号不需要转义
 * 4. 同理 (中文括号 中间可能有多个空格 \s*
 * 5. 全局匹配使用 g
 */

const regx5 = /\(\s*\)|(\s*)/g


yaogengzhu avatar Jun 22 '21 11:06 yaogengzhu

/**
 *  如何匹配位置, 有6个锚
 *  ^ $ \b \B (?=p) (?!p)、
 *
 *  ^ 脱字符 匹配开头, 在多行匹配中匹配开头
 *  $ 美元符匹配结尾,在多行匹配中匹配结尾
 *  \b 单词边界,具体是\w 和 \W 之间的位置,也包括\w与^之间的位置 和 $和^之间的位置
 *  \B 非单词边界
 *  (?=p) 其中p是一个模式,即p前面的位置,或者说,该位置后面的字符要匹配p ---> 正向先行断言 positive lookahead
 *  (?!p) ---> 负向先行断言 negative lookahead
 */

// 单行匹配
'hello'.replace(/^|$/g, '#'); // #hello#
// 多行匹配
"I\nlove\njavascript".replace(/^|$/gm, '#') // 每个单词前后加#
// 单词边界处理
"[JS] ILOVE.YOU".replace(/\b/g, '#') // "[#JS#] #ILOVE#.#YOU#"
// 非单词边界处理
"[JS] ILOVE.YOU".replace(/\B/g, '#'); // "#[J#S]# I#L#O#V#E.Y#O#U"

// (?=p) 匹配p前面的字符
"hello".replace(/(?=p)/g, '#') // he#l#lo

yaogengzhu avatar Jun 23 '21 01:06 yaogengzhu

 
/**
 *  数字的千分分隔符号表示法  1000,000,000
 *  1. 匹配末尾3个数的前面加一个 $末尾必须是数字开头,
 *  2. 3个数字组合可能上多个(\d{3})+
 *  3. 全局进行匹配 /g
 *  4. 且要求匹配的这个位置不能是开头 (?!^) 开头不替换
 * 
 * 
 */
const regx = /(?!^)(?=(\d{3})+$)/g
const str = '0100123456789' // 如果开头是0过滤处理
const str1 = str.replace(/^0+/, '').replace(regx, ',')  // 123,456,789
console.log(str1)

// 支持 12345678 123456789
const regx1 = /(?!\b)(?=(\d{3})+\b)/g
const str2 = '12345678 123456789'.replace(regx1, ',')
console.log(str2)


/**
 *  货币的格式化  1888  格式化 成$1888.00
 */

function format(num) {
    if (typeof num !== "number") return 'num必须为数字'
    return num.toFixed(2).replace(/(?!^)(?=(\d{3})+$)/g, ',').replace(/^/, "$ ")
}
console.log(format('123243626'))

如果考虑 100000000.000 这种数据结构,可以将 $ 后结尾替换成.

'1000000000.000'.replace(/(?!^)(?=(\d{3})+\.)/g, ',')

yaogengzhu avatar Jun 24 '21 02:06 yaogengzhu

正则实现一段字符串,截取某一段内容

const str = '我说:你好呀;'
const s = str.match(/我说:(\S*?);/)
// s[0]  你好呀

yaogengzhu avatar Aug 17 '21 11:08 yaogengzhu

实现单词字母转大写

const str = 'get-something-a-C'
function transformToUpperCase(str) {
    return str.replace(/\-./g, (s) => {
        return s.toLocaleUpperCase()
    }).replace(/\-/g, '')
}

yaogengzhu avatar Aug 24 '21 05:08 yaogengzhu

提取URL参数

const url = 'https://www.baidu.com/?a=1&b=3&d=4&sa=?3'
function getParamsByUrl(url) {
    const s = url.match(/\?.*/g).join('').substr(1)
    const obj = {}
    s.split('&').map(item => {
        obj[item.split('=')[0]] = item.split('=')[1]
    })
    return obj
}

yaogengzhu avatar Aug 24 '21 06:08 yaogengzhu

RegExp.prototype.exec()String.prototype.match()

exec() 方法在指定字符串中执行一个搜索匹配,结果返回一个数组或者null

语法

regexObj.exec(str)

match() 方法检索返回一个字符串匹配正则表达式的结果

语法

str.match(regexp)

如提取数字

'32323safa123'.match(/\d/g) //  ['3', '2', '3', '2', '3', '1', '2', '3']

yaogengzhu avatar Mar 25 '22 04:03 yaogengzhu

驼峰名明

function camelize (str) {
      return str.replace(/[-_\s]+(.)?/g, function (match, c) {
          return c ? c.toUpperCase() : '';
      });
  }
  console.log( camelize('-moz-transform') );
  // => "MozTransform"

yaogengzhu avatar Apr 12 '22 15:04 yaogengzhu

正则中使用变量

let d = 3
new RegExp(`(?!^)(?=(\\d{${d}})+$)`, 'g') //  /(?!^)(?=(d{3})+$)/g

yaogengzhu avatar May 16 '22 03:05 yaogengzhu

利用 Object.formEntries 似乎有点意思

const search = new URLSearchParams('https://github.com/yaogengzhu/daily-share/issues/130?a=b2'.match(/\?.*/g)[0].replace(/\?/g, ''))

Object.fromEntries(search)

Object.fromEntries()方法是Object.entries()的逆操作,用于将一个键值对数组转为对象。

yaogengzhu avatar Jun 08 '22 02:06 yaogengzhu

js 判断一个数字

/^([0-9]+\.?[0-9]*|-[0-9]+\.?[0-9]*)$/

yaogengzhu avatar Jun 10 '22 06:06 yaogengzhu

保留小数的处理方法

ThousandAndDecimal(num) {
	if(num) {
		return num.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
	} else {
		return '0.00'
	}
}

yaogengzhu avatar Aug 25 '22 09:08 yaogengzhu