summaryrefslogtreecommitdiffstats
path: root/Essentials/src/com/earth2me/essentials/utils/StringUtil.java
blob: cd6c579f673fb6e884a6c6cbca09a80e4d6b48c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.earth2me.essentials.utils;

import java.util.*;
import java.util.regex.Pattern;


public class StringUtil
{
	private static final Pattern INVALIDFILECHARS = Pattern.compile("[^a-z0-9-]");
	private static final Pattern INVALIDCHARS = Pattern.compile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]");

	//Used to clean file names before saving to disk
	public static String sanitizeFileName(final String name)
	{
		return safeString(name);
	}

	//Used to clean strings/names before saving as filenames/permissions
	public static String safeString(final String string)
	{
		return INVALIDFILECHARS.matcher(string.toLowerCase(Locale.ENGLISH)).replaceAll("_");
	}

	//Less restrictive string sanitizing, when not used as perm or filename
	public static String sanitizeString(final String string)
	{
		return INVALIDCHARS.matcher(string).replaceAll("");
	}

	public static String joinList(Object... list)
	{
		return joinList(", ", list);
	}

	public static String joinList(String seperator, Object... list)
	{
		StringBuilder buf = new StringBuilder();
		for (Object each : list)
		{
			if (buf.length() > 0)
			{
				buf.append(seperator);
			}

			if (each instanceof Collection)
			{
				buf.append(joinList(seperator, ((Collection)each).toArray()));
			}
			else
			{
				try
				{
					buf.append(each.toString());
				}
				catch (Exception e)
				{
					buf.append(each.toString());
				}
			}
		}
		return buf.toString();
	}
	private StringUtil()
	{
	}
}