从后端返回的任何长度的字符串都为"junkasdojf :text:"
我将如何使用reg表达式以":text:"
的形式返回干净的字符串(必须包含分号)
最好是一种快速的方式来处理此问题。以前没有使用过正则表达式,但我读到,除了进行讨厌的拆分和重建之外,这是解决此问题的唯一方法。
这是我到目前为止所掌握的,但是不确定如何前进
let regex = try? NSRegularExpression(pattern: ":[a-z]:", options: .caseInsensitive)
答案 0 :(得分:3)
使用range(of:options:)
会更简单。
let someStr = "junkasdojf :text:"
if let substrRange = someStr.range(of: ":[a-zA-Z]+:", options: .regularExpression) {
print("Match = \(someStr[substrRange])")
} else {
print("No match")
}
答案 1 :(得分:1)
以下将匹配多个匹配项
// \w matches any word character such as [a-zA-Z0-9_]
let regex = try! NSRegularExpression(pattern: ":\\w+:")
let nsString: NSString = "junkasdojf :text: flkasdj junkasdojf :two:"
let matches = regex.matches(in: nsString as String, options: [], range: NSMakeRange(0, nsString.length))
for match in matches {
print(nsString.substring(with: match.range))
}
答案 2 :(得分:1)
更通用的方法是使用捕获组:
let pattern = "junkasdojf\\s*(:[^:]*:)"
示例Swift代码:
let str = "Some string here, junkasdojf :text: and more here"
let pattern = "junkasdojf\\s*(:[^:]*:)"
do {
let regex = try NSRegularExpression(pattern: pattern)
if let match = regex.firstMatch(in: str, range: NSRange(str.startIndex..., in: str)) {
let result = str[Range(match.range(at: 1), in: str)!]
print(String(result))
}
} catch { print(error) }
请参见the regex demo。
在这里,junkasdojf
匹配作为您所需字符串左侧上下文的子字符串,\s*
匹配0+空格,(:[^:]*:)
将第一个冒号捕获到组1中,任意0 +除:
以外的其他字符,然后为:
。
或者,如果junkasdojf
和:
之间的空格数不能超过某个最大阈值,则可以使用基于约束宽度向后看的解决方案:
let s = "Some string here, junkasdojf :text: and more here"
if let rng = s.range(of: ":(?<=junkasdojf\\s{0,1000}:)[^:]*:", options: .regularExpression) {
print(s[rng])
}
这在regex101上不起作用,因为它不支持ICU regex风格,但是这假设junkasdojf
与下一个:
之间的空格不能超过1000个。 :(?<=junkasdojf\\s{0,1000}:)[^:]*:
与:
匹配,然后确保存在junkasdojf
,后跟0到1000个空格和一个:
(这对于锚定第一个:
是必要的),然后[^:]*
匹配除:
以外的零个或多个字符,然后:
匹配:
。
此外,如果您对最短的正则表达式感兴趣,但效率较低,则可以使用以下方法正则表达式替换输入字符串
let s = "Some string here, junkasdojf :text: and more here"
let result = s.replacingOccurrences(of: "(?s).*junkasdojf\\s*(:[^:]*:).*", with: "$1", options: .regularExpression, range: nil)
print(result)
输出::text:
。
请参见regex demo
详细信息
(?s)
-允许.
匹配换行符的修饰符.*
-尽可能多0个字符junkasdojf
-子字符串\\s*
-超过0个空格(:[^:]*:)
-捕获组1($1
):冒号,:
以外的0个或多个字符,冒号.*
-尽可能多0个字符答案 3 :(得分:1)
rmaddy的答案将是执行简单,不重复任务的首选方法,当您不介意在Swift代码中使用class A
{
protected static int a,b;
protected int c;
static A()
{
// a = 10;
Console.WriteLine("static A");
}
public A()
{
// a = 5;
Console.WriteLine("A Constructor");
// c = 0;
}
}
class B : A
{
static B()
{
b = 20;
// a = 30;
Console.WriteLine("Staic B");
// b = 20;
// a = 30;
}
public B()
{
Console.WriteLine("B Constructor");
// c = 4;
// a = 7;
}
}
class C : B
{
static C()
{
// a = 10;
Console.WriteLine("Static C");
}
public C()
{
Console.WriteLine("C Constructor");
// c = 0;
// a = 70;
}
}
static void Main(string[] args)
{
C c = new C();
Console.ReadKey();
}
时,AamirR的答案似乎是正确的解决方案。
但是NSString
与Swift NSRegularExpression
的基本用法如下:
String