我正在尝试从文件中提取一些 DNA 信息。由碱基 GCAT 组成的 DNA 数据之前是单词ORIGIN,之后是//. 如何编写正则表达式来获取这些标记之间的这些碱基?
我尝试了以下方法,但它不起作用。
[ORIGIN(GCATgcat)////]
样本数据:
ORIGIN
1 acagatgaag acagatgaag acagatgaag acagatgaag
2 acagatgaag acagatgaag acagatgaag acagatgaag
//
我正在尝试从文件中提取一些 DNA 信息。由碱基 GCAT 组成的 DNA 数据之前是单词ORIGIN,之后是//. 如何编写正则表达式来获取这些标记之间的这些碱基?
我尝试了以下方法,但它不起作用。
[ORIGIN(GCATgcat)////]
样本数据:
ORIGIN
1 acagatgaag acagatgaag acagatgaag acagatgaag
2 acagatgaag acagatgaag acagatgaag acagatgaag
//
试试这个模式“ \\b([GCATgcat]+)\\b”,它匹配由单词边界包围的任何 GCAT 字符序列(大写或小写)(因此它不会匹配嵌入在其他字符串中的那些字符,例如单词“catalog”)。如果您在示例文件中反复扫描此正则表达式,您将提取每个序列。
这是您的示例文件的一个工作示例:
// Locate the substring between "ORIGIN" and "//" in the file.
String fileContents = getSampleFileContents();
int indexOfOrigin = fileContents.indexOf("ORIGIN");
String pertinentSection = fileContents.substring(
indexOfOrigin, fileContents.indexOf("//", indexOfOrigin));
// Search for sequences within the pertinent substring.
Pattern p = Pattern.compile("\\b([GCATgcat]+)\\b");
Matcher m = p.matcher(pertinentSection);
List<String> sequences = new ArrayList<String>();
while (m.find()) {
sequences.add(m.group(1));
}
sequences.toString(); // => ["acagatgaag", "acagatgaag", ..., "acagatgaag"]
对于我们所有不是正则表达式超级向导的人,我建议采用两步法。删除明显的瑕疵,例如数字和换行符,然后进行匹配。例如
public class Regex {
static String NL = "\n";
static String INPUT = "stuff at beginning ORIGIN" + NL +
"1 acagatgaag acagatgaag acagatgaag acagatgaag" + NL + NL +
"2 acagatgaag acagatgaag acagatgaag acagatgaag" + NL +
"// I added stuff here at the end that should be ignored";
public static void main(String[] args) {
Pattern removePattern = Pattern.compile("[\\r\\n \\t\\d]+");
Pattern findPattern = Pattern.compile("ORIGIN[GCATgcat]+//");
Matcher removeMatcher = removePattern.matcher(INPUT);
String clean = removeMatcher.replaceAll("");
Matcher findMatcher = findPattern.matcher(clean);
if ( findMatcher.find()) {
System.out.println(findMatcher.group());
}
}
}