scala-news-reader
rss/atom news reader in scala
git clone https://9o.is/git/scala-news-reader.git
Helper.scala
(1443B)
1 package com.joereader.lib
2
3 object Helper {
4
5 implicit class ImplicitStringHelper(str: String) {
6 val Email = """(^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$)""".r
7
8 /* Checks if string is an email. */
9 def isEmail: Boolean = str match {
10 case Email(_) => true
11 case _ => false
12 }
13
14 /* Converts a string to a byte array. */
15 def str2bytes: Array[Byte] = str.toCharArray.map(_.toByte)
16
17 /* Converts a hex string to an array of bytes. */
18 def hex2bytes: Array[Byte] = {
19 str.replaceAll("[^0-9A-Fa-f]", "").sliding(2, 2).
20 toArray.map(Integer.parseInt(_, 16).toByte)
21 }
22
23 /* Converts all single quotes to double quotes. */
24 def singleQuoteToDouble: String = {
25 str.toList.map(_.toString).map(ch =>
26 if (ch == "'") "\"" else ch).mkString
27 }
28
29 /* Escapes characters in the string to make it "regex safe" */
30 def escape: String = {
31 val meta_regex = ".[]\\^$|?*+(){}"
32 str.toList.
33 map(_.toString).
34 map(ch =>
35 if (meta_regex.exists(c =>
36 ch.exists(_ == c))) "\\" + ch
37 else ch).
38 mkString
39 }
40 }
41
42 implicit class ImplicitByteArrayHelper(bytes: Array[Byte]) {
43
44 /* Converts a byte array to a string of hex. */
45 def bytes2hex: String = bytes.map("%02x" format _).mkString
46
47 /* Converts a byte array to its original string. */
48 def bytes2str: String = new String(bytes.map(_.toChar))
49 }
50 }